-
Notifications
You must be signed in to change notification settings - Fork 17
/
101-symmetric-tree.py
50 lines (45 loc) · 1.53 KB
/
101-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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def symmetric_helper(p, q):
if not p and not q:
return True
if not p and q:
return False
if p and not q:
return False
if p.val != q.val:
return False
return symmetric_helper(p.left, q.right) and symmetric_helper(p.right, q.left)
return symmetric_helper(root.left, root.right)
# time O(n), due to traverse
# space O(n), due to tree height
# using tree and divide and conquer and two branch top-down
from collections import deque
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
queue = deque()
queue.append(root.left)
queue.append(root.right)
while queue:
left = queue.popleft()
right = queue.popleft()
if not left and not right:
continue
elif not left or not right:
return False
elif left.val != right.val:
return False
queue.append(left.left)
queue.append(right.right)
queue.append(left.right)
queue.append(right.left)
return True
# time O(n)
# space O(n), due to queue and tree diameter
# using bfs (iterative)