leetcode Symmetric Tree(*)

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

Note:

Bonus points if you could solve it both recursively and iteratively.

      判断树本身是否自己的镜像树,即是否为中轴对称树。递归的思想很简单,保存树的左右节点,对于当前的两个节点,判断值是否相同,同时判断当前两个节点对称的 左右 和 右左 孩子是否相同,分辨以左右 右左孩子为当前节点进行递归。

class Solution {
public:
    bool isSymmetricRec(TreeNode *lRoot,TreeNode *rRoot){
        if(lRoot==NULL&&rRoot==NULL)return true;
        if(lRoot==NULL||rRoot==NULL)return false;
        return lRoot->val==rRoot->val&&isSymmetricRec(lRoot->left,rRoot->right)&&isSymmetricRec(lRoot->right,rRoot->left);
    }
    bool isSymmetric(TreeNode *root) {
        if(root==NULL)return true;
        return isSymmetricRec(root->left,root->right);
    }
};
      对于迭代,一层一层的遍历比较,设前一层为ver[pre],存储的前一层的成对的相同的节点,设当前层为ver[cur],则由pre层生成cur层。这里存储的形式为对称的一对一对的节点,故数组的遍历步长为2.

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(root==NULL)return true;
        vector<TreeNode*> ver[2];
        int pre=1,cur=0;
        if(root->left==NULL&&root->right==NULL)return true;
        else if(root->left==NULL||root->right==NULL)return false;
        else if(root->left->val!=root->right->val)return false;
        ver[cur].push_back(root->left);ver[cur].push_back(root->right);
        while(ver[cur].size()>0){
            cur=!cur;
            pre=!pre;
            ver[cur].clear();
            for(int i=0;i<ver[pre].size();i+=2){
                if(ver[pre][i]->left==NULL&&ver[pre][i+1]->right==NULL);
                else if(ver[pre][i]->left==NULL||ver[pre][i+1]->right==NULL)return false;
                else if(ver[pre][i]->left->val!=ver[pre][i+1]->right->val)return false;
                else{
                    ver[cur].push_back(ver[pre][i]->left);ver[cur].push_back(ver[pre][i+1]->right);
                }
                if(ver[pre][i]->right==NULL&&ver[pre][i+1]->left==NULL);
                else if(ver[pre][i]->right==NULL||ver[pre][i+1]->left==NULL)return false;
                else if(ver[pre][i]->right->val!=ver[pre][i+1]->left->val)return false;
                else{
                    ver[cur].push_back(ver[pre][i]->right);ver[cur].push_back(ver[pre][i+1]->left);
                }
            }
        }
        return true;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值