101. Symmetric Tree
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def isSymmetric(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: bool 13 """ 14 if not root: return True 15 return self.helper(root.left, root.right) 16 17 def helper(self, left, right): 18 # first make sure left and right is not none 19 if left and right: 20 if left.val == right.val: 21 return self.helper(left.left, right.right) and self.helper(left.right, right.left) 22 else: 23 return False 24 else: 25 # otherwise,return left == right 26 return left == right
以上是关于101. Symmetric Tree的主要内容,如果未能解决你的问题,请参考以下文章