欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

101. Symmetric Tree

程序员文章站 2022-05-18 19:38:57
...

problems:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.
tips:
判断二叉树是否对称,假设有两个节点n1和n2,若树平衡,则n1的左子树的值等于n2右子树的值,n1右子树的值等于n2左子树的值。
solution:

class Solution {
public:
    bool isSymmetric(TreeNode* left,TreeNode* right)
{
    if(!left && !right) return true;
    if((!left && right)||(left && !right)||(left->val!=right->val)) return false;
    return isSymmetric(left->left,right->right)&&isSymmetric(left->right,right->left);
}
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return isSymmetric(root->left,root->right);
    }
};
相关标签: tree