LeetCode 之 Symmetric Tree

原创 2013年12月05日 22:54:24

原题:

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
这个题利用递归非常好解,每次判定两个节点,看这两个节点是否对称就行。假如当前判定的是node1和node2:

1 如果node1和node2都为null,对称

2 如果node1和node2都不为null,如果node1->val == node2->val,还不一定对称,需要判定node1的左和node2的右是否对称;node1的右和node2的左是否对称。

3 如果node1和node2有一个不为null,则不对称

代码(32ms):

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if(!root) return true;
        return two_compare(root->left , root->right);
    }
    
    bool two_compare(TreeNode * leftTree , TreeNode * rightTree){
        
        if(leftTree && rightTree){
            if(leftTree->val != rightTree->val){
                return false;
            }
            return ( two_compare(leftTree->left,rightTree->right) && two_compare(leftTree->right,rightTree->left) );
        }
        else if(!leftTree && !rightTree){
            return true;
        }
        else {
            return false;
        }
        
    }
    
};

相关文章推荐

【LeetCode】Symmetric Tree

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

leetcode || 101、Symmetric Tree

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

【LeetCode】Symmetric Tree

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

Symmetric Tree -- LeetCode

原题链接: http://oj.leetcode.com/problems/symmetric-tree/  这道题是树的题目,本质上还是树的遍历。这里无所谓哪种遍历方式,只需要对相应结点进行比较即可...

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(Symmetric Tree)判断二叉树是否是对称的

题目要求: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its cen...
  • lqcsp
  • lqcsp
  • 2014年04月15日 05:25
  • 542

[leetcode] 101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). Fo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode 之 Symmetric Tree
举报原因:
原因补充:

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