题目:
解答:
采用递归, 根据定义,一个树是镜像树,那么他的左子树的左右子树分别和右子树的右左子树为镜像树。
代码:
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (root == NULL)
return true;
return search(root->left, root->right);
}
bool search(TreeNode *leftNode, TreeNode *rightNode)
{
if (leftNode == NULL && rightNode == NULL)
return true;
if (leftNode == NULL || rightNode == NULL)
return false;
return (leftNode->val == rightNode->val) && search(leftNode->left, rightNode->right) && search(leftNode->right, rightNode->left);
}
};