Leetcode 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 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.
循环
class Solution(object): def isSymmetric(self, root): stack = [root] while stack: value = [x.val if x else None for x in stack] if value[::-1] != value: return False stack_new = [] for x in stack: if x: stack_new += [x.left,x.right] stack = stack_new return True
递归
注意判断顺序
class Solution(object): def isSymmetric(self, root): return True if not root else self.sym(root.left, root.right) def sym(self, l, r): if not l and not r: return True if not l or not r: return False if l.val != r.val: return False return self.sym(l.left,r.right) and self.sym(l.right,r.left)