101. Symmetric Tree | LeetCode Using Python
In this video, I solve the LeetCode problem “101. Symmetric Tree” using both recursive and iterative DFS approaches in Python. I walk through each method to check if a binary tree is symmetric around its center, demonstrating the algorithm’s effectiveness in ensuring mirrored node values and structure. Below is the code used to solve this problem:
# 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:
#recursive approach
#Time Complexity: O(n) - all nodes are visite donce
#Space Complexity: O(H) H being height - in a balance tree --> it is a O(logn) ; in a skewed tree --> it is O(n)
#let's make a helper function
def symmetric_check(node1, node2):
#Base case
if node1 is None and node2 is None:
return True
if node1 is None or node2 is None:
return False
return (node1.val == node2.val) and symmetric_check(node1.left, node2.right) and symmetric_check(node1.right, node2.left)
return symmetric_check(root, root)
'''
#iteratively approach - Has more advantage for deeper tree than recursive
#Time Complexity: O(n) - all nodes are visite donce
#Space Complexity: O(H) H being height - in a balance tree --> it is a O(logn) ; in a skewed tree --> it is O(n)
if root is None:
return None
stack = [(root.left, root.right)] #Tuple in our stack
while stack:
node1, node2 = stack.pop()
if node1 is None and node2 is None:
continue
if node1 is None or node2 is None:
return False
if node1.val != node2.val:
return False
stack.append((node1.left,node2.right))
stack.append((node1.right, node2.left))
return True
'''