101. Symmetric Tree ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Binary Tree
, DFS
, BFS
, Recursion
, Iteration
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
The number of nodes in the tree is in the range [1, 1000]
.
-100 <= Node.val <= 100
.
Can you solve it both recursively and iteratively?
To determine if a binary tree is symmetric:
Compare the left and right subtrees to see if they are mirrors of each other.
Perform this comparison recursively or iteratively.
Recursive Approach:
Compare the root's left and right subtrees.
Recursively check the symmetry of the outer and inner pairs of nodes.
Iterative Approach:
Use a queue to compare nodes in a level-order fashion.
Add pairs of nodes to the queue, ensuring the outer and inner children are paired.
O(n), where n
is the number of nodes in the tree. Each node is visited once.
O(h) for the recursive approach, where h
is the height of the tree (stack space for recursion).
O(n) for the iterative approach due to the queue.
Can you solve this problem for a multi-ary tree?
What modifications would you make if the tree's symmetry condition depended on node depth?