LC101 Binary Tree Symmetry
几种方法:
1)recursively compare two mirror trees, check if corresponding element is equal.
2) Using Stacks,(use list to append and pop, not memory efficient; use collections.deque to create stack, since this is built on doubly linked list, better for push and pop operations, more memory efficient)
3) Using level-order traversal, 每traverse一个level,成为一个新的list,检查其是否为对称的list
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
"""
def isMirror(t1, t2):
if t1==None and t2==None:
return True
elif t1==None or t2==None:
return False
else:
return ((t1.val == t2.val) and isMirror(t1.right, t2.left) and isMirror(t1.left, t2.right))
return isMirror(root, root)
"""
def isSymmetric(self, root):
if root is None:
return True
stack = [(root.left, root.right)]
while stack:
left, right = stack.pop()
if left is None and right is None:
continue
if left is None or right is None:
return False
if left.val == right.val:
stack.append((left.left, right.right))
stack.append((left.right, right.left))
else:
return False
return True
#### A better version of using stack.
# stack used to hold the matching pairs
stack = []
# if root=None, or if root has no children, root is symmetric
if not root or (not root.left and not root.right):
return True
stack.append((root.left, root.right))
while len(stack):
# the order of node retrieval matters little here, because we only care about
# pair content and not the relative order of different pairs; queue is quicker
# at finding shallow discrepancy, where stack is quicker at finding deeper
# discrepancy
left, right = stack.pop()
# if left and right are not symmetric, return false
if not left or not right or (left.val != right.val):
return False
# only append if the corresponding pairs exist
if left.left or right.right:
stack.append((left.left, right.right))
if left.right or right.left:
stack.append((left.right, right.left))
return True
def isSymmetric(self, root):
last = [root]
while True:
if not any(last):
return True
current = []
for node in last:
if node is not None:
current.append(node.left)
current.append(node.right)
if not self.is_list_symmetric(current):
return False
else:
last = current
def is_list_symmetric(self, lst):
head, tail = 0, len(lst) - 1
while head < tail:
h, t = lst[head], lst[tail]
head += 1
tail -= 1
if h == t == None:
continue
if None in (h, t) or h.val != t.val:
return False
return True
```