Tree Symmetric Check
Given an array representing a binary tree in level-order, determine whether the tree is symmetric around its center (a mirror image of itself). Return true if it is symmetric, false otherwise.
For example, the tree [1, 2, 2, 3, 4, 4, 3] is symmetric. The tree [1, 2, 2, null, 3, null, 3] using -1 for null is not symmetric. An empty tree or single-node tree is symmetric.
A symmetric tree means the left subtree is a mirror reflection of the right subtree. For each pair of corresponding nodes, their values must be equal, and the left child of the left node must mirror the right child of the right node.
The solution uses a queue-based approach: enqueue pairs of nodes to compare. Dequeue a pair, check if both are null (continue), if one is null (return false), or if their values differ (return false). Then enqueue the next mirror pairs.
Edge cases include an empty tree (true), a single node (true), a tree where values match but structure does not (false), and a tree where structure matches but values do not (false).
Example Input & Output
Symmetric
Another symmetric
Not symmetric: 4!=5
Not symmetric: 2!=3
Single node
Algorithm Flow
Solution Approach
Use a queue to compare mirrored node pairs level by level.
Handle trivial cases. Start with the left and right children of root (indices 1 and 2). For each pair, check bounds and values. Then enqueue the mirror pairs: left's left with right's right, and left's right with right's left.
Time complexity is O(n), space complexity is O(n) for the queue.
Best Answers
class Solution {
public boolean solution(int[] nums) {
int n=nums.length;if(n<=1)return true;
for(int i=0;i<n;i++){
int lv=31-Integer.numberOfLeadingZeros(i+1);
int first=(1<<lv)-1,last=(1<<(lv+1))-2,mirror=first+last-i;
if(mirror<n&&nums[i]!=nums[mirror])return false;
}return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
