Coding Problems
Symmetric Tree | Leetcode 101
Welcome to our deep dive on Symmetric Tree (Leetcode 101). This problem extends standard DFS patterns by requiring simultaneous traversal of two separate tree branches.
Problem Statement
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
root = [1,2,2,3,4,4,3] => Output: true
Example 2:
root = [1,2,2,null,3,null,3] => Output: false
Approach: Recursive Mirrored DFS O(N)
To determine if a tree is symmetric, its root's left subtree and right subtree must be perfectly mirrored reflections of each other.
To prove two subtrees left_node and right_node are mirrored, they must fulfill three combined conditions:
- Their root values must be identical.
- The
left_node.leftsubtree must mirror theright_node.rightsubtree. - The
left_node.rightsubtree must mirror theright_node.leftsubtree.
We can solve this intuitively using DFS by passing down two separate node pointers concurrently.
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def isMirror(left_node, right_node):
if not left_node and not right_node:
return True
if not left_node or not right_node:
return False
return (left_node.val == right_node.val) and \
isMirror(left_node.left, right_node.right) and \
isMirror(left_node.right, right_node.left)
return isMirror(root.left, root.right)
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time | O(N) | We traverse the whole binary tree. Even though we iterate with two distinct pointers simultaneously, we process exactly half the overall total nodes per pointer, yielding O(N/2 * 2) -> O(N). |
| Space | O(H) | The memory overhead matches the tree's maximum height exactly due to the recursive stack depth H. |