美文网首页
[Leetcode]101. Symmetric Tree

[Leetcode]101. Symmetric Tree

作者: 木易yr | 来源:发表于2019-08-17 22:59 被阅读0次

    101. Symmetric Tree

    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.
    题意:对称(镜像)二叉树
    思路:什么是对称(镜像)二叉树?
    1.两个根结点的值要相等
    2.左边的左子树和右边的右子树对称
    3.左边的右子树和右边的左子树对称
    注意:
    1.空结点对称
    2.如果左子树和右子树只有一个为空则不对称

    /**
     * Definition for a binary tree node.
     * 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;
            return dfs(root->left,root->right);
        }
        bool dfs(TreeNode*p,TreeNode*q)
        {
            if(!p||!q)
                return !p && !q;//如果左子树和右子树只有一个为空则不对称
            return p->val==q->val&&dfs(p->left,q->right)&&dfs(p->right,q->left);
            
        }
    };
    

    迭代:

    /**
     * Definition for a binary tree node.
     * 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;
            stack<TreeNode*>left,right;
            auto l=root->left,r=root->right;
            while(l||r||left.size()||right.size())
            {
                while(l&&r)
                {
                    left.push(l),
                    l=l->left;
                    right.push(r);
                    r=r->right;    
                }        
                if(l||r)
                    return false;
                l=left.top(),left.pop();
                r=right.top(),right.pop();
                if(l->val!=r->val)
                    return false;
                l=l->right,r=r->left;
            }
            return true;
        }
    };
    

    相关文章

      网友评论

          本文标题:[Leetcode]101. Symmetric Tree

          本文链接:https://www.haomeiwen.com/subject/kuklsctx.html