-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0101_symmetric-tree.py
61 lines (46 loc) · 1.4 KB
/
0101_symmetric-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
# recursion
def isSymmetric(self, root):
return self.isMirror(root.left, root.right)
def isMirror(self, a, b):
if not a and not b:
return True
if not a or not b:
return False
if a.val != b.val:
return False
return self.isMirror(a.left, b.right) and self.isMirror(a.right, b.left)
# iteration
def isSymmetric2(self, root):
q = deque([root.left, root.right])
while len(q) > 0:
a, b = q.popleft(), q.popleft()
if not a and not b:
continue
if not a or not b:
return False
if a.val != b.val:
return False
q.append(a.left)
q.append(b.right)
q.append(a.right)
q.append(b.left)
return True
if __name__ == '__main__':
root = TreeNode(1,
TreeNode(2,
TreeNode(3), TreeNode(4)),
TreeNode(2,
TreeNode(4), TreeNode(3)))
s = Solution()
b = s.isSymmetric(root)
print(b)
b2 = s.isSymmetric(root)
print(b2)