[Leetcode]101. Symmetric Tree

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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容