Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- # 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 isLevelSymmetric(self, level_arr: list) -> bool:
- for i in range(math.ceil(len(level_arr) / 2)):
- if level_arr[i] != level_arr[-1-i]:
- return False
- return True
- def isSymmetric(self, root: TreeNode) -> bool:
- # Keep track of current level so I know when to check for symmetry
- curr_level = 0
- # Store level array to check symmetry
- level_arr = []
- # BFS
- queue = deque([{
- 'node': root,
- 'level': 0
- }])
- while len(queue) > 0:
- curr_node_dict = queue.popleft()
- # Extract node for convenience
- curr_node = curr_node_dict['node']
- # Extract curr_node_val for the case where curr_node is None
- if curr_node:
- curr_node_val = curr_node.val
- else:
- curr_node_val = None
- # Once finish a level, check if that level is symmetric
- if curr_node_dict['level'] > curr_level:
- # If not symmetric, return False
- if not self.isLevelSymmetric(level_arr):
- return False
- # Else continue, reset level_arr, increment curr_level
- level_arr = [curr_node_val]
- curr_level += 1
- # If still on same level, append curr node's value to level_arr
- else:
- level_arr.append(curr_node_val)
- # If curr_node is None, do not attempt to add children to queue
- if not curr_node:
- continue
- # Add left child to the queue
- queue.append({
- 'node': curr_node.left,
- 'level': curr_node_dict['level'] + 1
- })
- # Add right child to the queue
- queue.append({
- 'node': curr_node.right,
- 'level': curr_node_dict['level'] + 1
- })
- # If reached end of tree (i.e. finished BFS, i.e. queue is empty), return True
- return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement