101. Symmetric Tree ๐
Difficulty: Easy
- Tags: Binary Tree
, DFS
, BFS
, Recursion
, Iteration
Problem Statement ๐
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Examples ๐
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
Constraints โ๏ธ
The number of nodes in the tree is in the range
[1, 1000]
.-100 <= Node.val <= 100
.
Follow-up ๐ง
Can you solve it both recursively and iteratively?
Solution ๐ก
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.
Java Solution (Recursive Approach)
Java Solution (Iterative Approach)
Explanation of the Solutions
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.
Time Complexity โณ
O(n), where
n
is the number of nodes in the tree. Each node is visited once.
Space Complexity ๐พ
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.
Follow-up Challenges ๐ง
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?
Last updated