Tree Same Tree
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
Different sizes
Single node
Different values
Identical trees
Different sizes
Algorithm Flow
Solution Approach
Compare the two arrays element by element after checking for equal length.
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
class Solution {
public boolean solution(int[] a, int[] b) {
return java.util.Arrays.equals(a,b);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
