-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0101-symmetric-tree.py
31 lines (27 loc) · 1.08 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
# 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:
if not root.left and not root.right:
return True
queueLeft = deque()
queueRight = deque()
queueLeft.appendleft(root.left)
queueRight.appendleft(root.right)
while queueLeft and queueRight:
nodeLeft, nodeRight = queueLeft.pop(), queueRight.pop()
if not nodeLeft and not nodeRight:
continue
# both node must exist
# if exists thet must have the same value
if not nodeLeft or not nodeRight or nodeLeft.val != nodeRight.val:
return False
queueLeft.appendleft(nodeLeft.left)
queueLeft.appendleft(nodeLeft.right)
queueRight.appendleft(nodeRight.right)
queueRight.appendleft(nodeRight.left)
return not (queueLeft or queueRight)