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

分析如下:这道题目最好用递归的方式
递归的思路在于只是给定函数一个边界的限制条件然后让计算机在栈中自行的推导和计算
我们限定的条件是:1 当左边的左子树和右边的右子树(或者是左边的右子树和右边的左子树) 不相等的时候则不是对称树
2 当顶点是null的时候,没有二叉树的时候 算作对称。
int Symetric(struct TreeNode* q, struct TreeNode* p)   //one is for left tree another is for right tree
{
    if(!q && !p ) return true;                  //if q and p equal to null equal then
    if(!q || !p) return false;
    else
    {
        return (q->val == p->val)&&Symetric(q->left, p->right)&&(Symetric(q->right, p->left));
        
    }
    return false;
}



bool isSymmetric(struct TreeNode* root){
   
    
    if(root == NULL)
        return true;
    else 
        return Symetric(root->left, root->right);
}

 

posted on 2020-04-22 06:45  闲云潭影  阅读(148)  评论(0编辑  收藏  举报