Code Logo

Tree Symmetric Check

Published at25 Jul 2026
Binary Tree Easy 1 views
Like0

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

Example 1
Input
[1,2,2,3,4,4,3]
Output
true
Explanation

Symmetric

Example 2
Input
[1,2,2,3,5,5,3]
Output
true
Explanation

Another symmetric

Example 3
Input
[1,2,2,3,4,5,3]
Output
false
Explanation

Not symmetric: 4!=5

Example 4
Input
[1,2,3]
Output
false
Explanation

Not symmetric: 2!=3

Example 5
Input
[1]
Output
true
Explanation

Single node

Algorithm Flow

Recommendation Algorithm Flow for Tree Symmetric Check

Solution Approach

Use a queue to compare mirrored node pairs level by level.

function isSymmetric(arr)
  if length(arr) <= 1 then return true
  q = [1, 2]
  while q is not empty
    left = pop front of q, right = pop front of q
    if left >= length(arr) and right >= length(arr) then continue
    if left >= length(arr) or right >= length(arr) then return false
    if arr[left] != arr[right] then return false
    add 2*left+1 to q; add 2*right+2 to q
    add 2*left+2 to q; add 2*right+1 to q
  return true

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

java
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;
    }
}