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

[Tree]101. Symmetric Tree

作者: 野生小熊猫 | 来源:发表于2019-02-22 10:30 被阅读0次
  • 分类:Tree/BackTracking
  • 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
  • 空间复杂度: O(h) 树的节点的深度

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.

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: 'TreeNode') -> 'bool':
        
        if root==None:
            return True
        
        res=self.helper(root.left,root.right)
        return res
    
    def helper(self,left,right):
        if left==None and right==None:
            return True
        elif left==None or right==None:
            return False
        else:
            if left.val==right.val:
                return self.helper(left.right,right.left) and self.helper(left.left,right.right)
            else:
                return False

讨论:

1.这道题是道简单的好题,思路看代码就成了!

相关文章

网友评论

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

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