101. Symmetric Tree

原创 2016年05月31日 16:01:25

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

思路:基本上树的题就是迭代和遍历两种啦。

这道题一开始觉得有点难,因为root为空的时候应该返回true,但是如果迭代的话,当叶子节点变成root的时候应该返回false。也忘记考虑不仅结构要对称,而且值也要对称。

最后解决方案如下:

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(!root) return 1;
        return helper(root->left,root->right);
    }
    
    bool helper(TreeNode* left,TreeNode* right){
        if(!left&&!right)return 1;
        else if(!left||!right) return 0;
        
        if(left->val!=right->val) return 0;
        
        return helper(left->left,right->right)&&helper(left->right,right->left);
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

101. Symmetric Tree

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

101:Symmetric Tree【树】【DFS】

题目链接:click~ :解法1:队列 /*题意:判断一颗二叉树是否是自己的镜像*/ /** *思路: 只要保证根结点下的左子树的每一层是右子树的镜像,此树是自己的镜像 * ...

LeetCode 101. Symmetric Tree

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

leetcode || 101、Symmetric Tree

problem: Given a binary tree, check whether it is a mirror of itself (ie, symmetric aro...

LeetCode#101. Symmetric Tree

101. Symmetric Tree Given a binary tree, check whether it is a mirror of itself (ie, symmetric aroun...

【Leetcode】101. Symmetric Tree

方法一:递归: 思路: (1)若树为空,直接返回true。否则调用判断左右子树是否对称的函数isSymmetricTree(root.left, root.right)。 (2)判断左右子树是否对称:...

101. Symmetric Tree Leetcode Python

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

[LeetCode]101.Symmetric Tree

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

LeetCode 101. Symmetric Tree

101. Symmetric Tree一、问题描述 Given a binary tree, check whether it is a mirror of itself (ie, symmetr...

[leetcode] 101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). Fo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)