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
Note:
Bonus points if you could solve it both recursively and iteratively.
这道题目要求iterative 和recursive的解法。
recursive的解法比较简练
1.停止条件是 left==None & right==None
2. left.val==right.val 比较left.left right.right & left.right right.left
任何条件不成立都是false
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def sym(self,left,right): if left==None and right==None: return True if left and right and left.val==right.val: return self.sym(left.left,right.right) and self.sym(left.right,right.left) else: return False def isSymmetric(self, root): if root==None: return True return self.sym(root.left,root.right)
1.先将left 和right 依次存入stack1 stack2
2.当stack非空的时候将node pop出来 依次往下取left 和right
进行比较
代码如下
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def sym(self,left,right): if left==None and right==None: return True if left and right and left.val==right.val: return self.sym(left.left,right.right) and self.sym(left.right,right.left) else: return False def isSymmetric(self, root): if root==None: return True if root.left==None and root.right==None: return True if root.left==None or root.right==None: return False stack1=[] stack2=[] stack1.append(root.left) stack2.append(root.right) while len(stack1)!=0 and len(stack2)!=0: n1=stack1.pop() n2=stack2.pop() if n1.val!=n2.val: return False #if n1.left==None or n2.right==None: # return False #if n1.right==None or n2.left==None: # return False if n1.left==None and n2.right!=None or n1.left!=None and n2.right==None: return False if n1.right==None and n2.left!=None or n1.right!=None and n2.left==None: return False if n1.left and n2.right: stack1.append(n1.left) stack2.append(n2.right) if n1.right and n2.left: stack1.append(n1.right) stack2.append(n2.left) return True
101. Symmetric Tree Leetcode Python
原文地址:http://blog.csdn.net/hyperbolechi/article/details/43302333