Code Logo

Tree Same Tree

Published at25 Jul 2026
Binary Tree Easy 1 views
Like0

Given two arrays representing complete binary trees in level-order, determine whether the two trees are structurally identical and contain the same values. Two trees are considered the same if they have the same structure and every corresponding node has the same value.

For example, [1, 2, 3] and [1, 2, 3] are the same tree. [1, 2] and [1, 2, 3] are not the same (different structure). [1, 2, 3] and [1, 3, 2] are not the same (values differ at positions). Two empty arrays are the same tree (both empty).

Checking whether two trees are identical is a fundamental tree comparison operation. It tests your understanding of tree traversal — you must visit corresponding nodes in both trees simultaneously and verify that both the structure and values match at each position.

In the array-based representation, two trees are identical if their arrays have the same length and every element at each index is equal. This is because the level-order array encodes both structure and values: the same index always represents the same position in the tree.

Edge cases include both trees being empty (identical), one tree being empty and the other not (different), and trees with the same values but different structures (different lengths cause different structures).

Example Input & Output

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

Different sizes

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

Single node

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

Different values

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

Identical trees

Example 5
Input
[],[1]
Output
false
Explanation

Different sizes

Algorithm Flow

Recommendation Algorithm Flow for Tree Same Tree

Solution Approach

Compare the two arrays element by element after checking for equal length.

function solution(a, b) {
  if (a.length !== b.length) return false;
  for (var i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

First check if the arrays have the same length — if not, the trees cannot be identical because they have different numbers of nodes. Then iterate through each index and compare values. If any pair differs, return false. If all pairs match, return true.

Time complexity is O(n) where n is the number of nodes. Space complexity is O(1).

Best Answers

java
class Solution {
    public boolean solution(int[] a, int[] b) {
        return java.util.Arrays.equals(a,b);
    }
}