Code Logo

Tree Symmetric Check

Published at25 Jul 2026
Binary Tree Easy 0 views
Like0

Check if a binary tree represented as an array is symmetric around its center (a mirror of itself). A tree is symmetric if the left subtree is a mirror of the right subtree.

For array representation, compare pairs of nodes at mirror positions across the root. At each level, the leftmost and rightmost nodes should match, moving inward.

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
Recommendation Algorithm Flow for Tree Symmetric Check

Solution Approach

function solution(arr) {
  if (arr.length <= 1) return true;
  var n = arr.length;
  for (var i = 0; i < n / 2; i++) {
    var level = Math.floor(Math.log2(i + 1));
    var first = Math.pow(2, level) - 1;
    var last = Math.pow(2, level + 1) - 2;
    var mirror = first + last - i;
    if (mirror < n && arr[i] !== arr[mirror]) return false;
  }
  return true;
}

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