Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Codes
Method 1: Recursive
1
2
3
4
5
6
7
8
9
def(self, root):
defisMirror(left, right):
if(not left andnot right):
returnTrue
if(not left ornot right):
returnFalse
return (left.val==right.val) and
isMirror(left.left, right.right) and isMirror(left.right, right.left)
return isMirror(root, root)
This method use a helper function isMirror which receive two nodes and check if they are symmetric. Then by recursive along all the path of the tree to determine if the tree is symmetric.
Method 2: Iterative
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def(self, root):
import Queue
q=Queue.Queue()
q.put(root)
q.put(root)
while(not q.empty()):
left=q.get()
right=q.get()
if(not left andnot right):
continue
if(not left ornot right):
returnFalse
if(left.val!=right.val):
returnFalse
q.put(left.right)
q.put(right.left)
q.put(left.left)
q.put(right.right)
returnTrue
This method uses a queue to push in pairs of nodes that should have the same value.
近期评论