I am writing code to solve the following leetcode problem: https://leetcode.com/problems/symmetric-tree/
The problem in a nutshell is "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center)."
from collections import deque
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue= deque()
if not root:
return []
#add left and right child of root to start (if root is not None)
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
right_subt = []
left_subt = []
while queue:
level_length = len(queue)
#iterate over each level of the tree and add left subtree to left_subt and right subtree to right_subt
for _ in range((level_length//2)+1):
node = queue.popleft()
left_subt.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
for _ in range((level_length-(level_length//2))+1):
node = queue.popleft()
right_subt.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
#compare left and right subtree at each level to check if they're the same
if left_subt !=right_subt.reverse():
return False
#reinitialize left and right subtree lists
left_subt = []
right_subt = []
return True
I have run the algorithm with the following input: [1,2,2,3,4,4,3]
; it is the input that you see at the top of the page when you click on the link to Leetcode above.
It is returning false
when it should be returning true
. When I run the input on paper it seems to work, but unlike arrays/strings, I am not sure how to print
node values at each stage. Any ideas how to do this, or can someone please outline where the code falls short?