I have a working recursive solution to check if a binary tree is symmetric. The code works correctly for my test cases, but I'm concerned about potential stack overflow with deep trees since Python has a default recursion limit.
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):
if root is None:
return True
return self.compare(root.left, root.right)
def compare(self, nodeA, nodeB):
if nodeA is None and nodeB is None:
return True
if nodeA is None or nodeB is None:
return False
if nodeA.val != nodeB.val:
return False
return (self.compare(nodeA.left, nodeB.right) and
self.compare(nodeA.right, nodeB.left))
These are the test cases that works:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.right.right = TreeNode(3)
sol = Solution()
print(sol.isSymmetric(root)) # Output: True
The problem is when testing with a tree that has depth > 1000 nodes, I get:
RecursionError: maximum recursion depth exceeded in comparison
I understand this is O(n) time complexity which is optimal, but the recursive approach uses O(h) space on the call stack where h is tree height.
How can I convert this recursive solution to an iterative one using an explicit stack or queue to avoid Python's recursion limit while maintaining the same comparison logic (mirrored left-right traversal)?
I've tried using a single stack but I'm not sure how to properly track both subtrees simultaneously for the mirrored comparison.
def isSymmetric(self, root):
if not root:
return True
stack = [(root.left, root.right)]
# Not sure how to proceed from here to compare nodes correctly
What's the correct way to manage the stack to compare pairs of nodes in mirror order?