Symmetric Tree(递归和非递归方法) ——Difficulty:Easy

Problem :

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

Example:

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

**

Algorithm:

**
方法1:递归,对左边节点的右子树和右边节点的左子树递归,以及左边节点的左子树和右边节点的右子树递归(因为是对称的)

方法2:非递归,对根节点的左子树,和右子树分别作层次遍历,左子树做从左到右的层次遍历,右子树做从右到左的层次遍历。每次取出两个队列的队首进行比较,要注意的是如果两个节点的对应子树如果一个是空另一个非空,那么就已经说明两个树不是对称的了,如果不管空子树,直接层次遍历,就会出现例子中错误。

**

Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 方法1class Solution {
public:
    bool is(TreeNode* root1,TreeNode* root2)
    {
        if(root1==NULL&&root2==NULL)
            return true;
        if(root1==NULL||root2==NULL)
            return false;
        if(root1->val==root2->val)
        {
            return is(root1->left,root2->right)&&is(root1->right,root2->left);
        }
        return false;
    }
    bool isSymmetric(TreeNode* root) {
       if(root==NULL)
        return true;
        return is(root->left,root->right);
    }

};

方法2class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL||(root->left==NULL&&root->right==NULL))
            return true;
        if((root->left==NULL&&root->right!=NULL)||(root->right==NULL&&root->left!=NULL))
        {
            return false;
        }
        queue<TreeNode*> q1;
        queue<TreeNode*> q2;
        q1.push(root->left);
        q2.push(root->right);bool A=true;
        while(!q1.empty())
        {
            TreeNode* t1=q1.front();
            TreeNode* t2=q2.front();
            q1.pop();
            q2.pop();
            if(t1->val!=t2->val)
            {
                A=false;
                break;
            }
            else
            {

                if((t1->left==NULL&&t2->right!=NULL)||(t1->right==NULL&&t2->left!=NULL))
                {
                    A=false;
                    break;
                }
                else
                {
                    if(t1->left)q1.push(t1->left);
                    if(t1->right)q1.push(t1->right);
                    if(t2->right)q2.push(t2->right);
                    if(t2->left)q2.push(t2->left);
                }

            }
        }
        return A;
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值