Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
思路:对于根结点,若其不为空,则判断其左右子树是否都存在,且左右子树的根结点值必须相同,否则该树就不对称。然后继续判断这两颗左右子树是否对称。令左子树为L,右子树为R,需要做的就是判断L的左子树和R的右子树,他们的根结点值是否相同;还有L的右子树和R的左子树,他们的根结点值是否相同。(前提是左右子树必须都存在,如果有一方不存在,那么就不对称)。上述方法可以采用递归实现。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSymmetric(TreeNode *root)
{
if(!root)
return true;
else
return judge(root->left,root->right);
}
bool judge(TreeNode* p, TreeNode* q)
{
if(!p && !q)
return true;
else if(p && q && p->val == q->val)
return judge(p->left,q->right) && judge(p->right,q->left);
else
return false;
}
};