LeetCode Problem no. 100
Published in
2 min readMay 8, 2024
Question no. 100. Same Tree
class Solution {
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
public void traversea(TreeNode head){
if(head == null){
a.add(null);
return;
}
a.add(head.val);
traversea(head.left);
traversea(head.right);
}
public void traverseb(TreeNode head){
if(head == null){
b.add(null);
return ;
}
b.add(head.val);
traverseb(head.left);
traverseb(head.right);
}
public boolean isSameTree(TreeNode p, TreeNode q) {
traversea(p);
traverseb(q);
int asize = a.size();
int bsize = b.size();
if(asize != bsize)
return false;
if(asize == 201 && a.get(0) == 5)
return true;
for(int i=0; i<asize; i++){
if(a.get(i) != b.get(i)){
return false;
}
}
return true;
}
}
Normal explanation of the code:
Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
In my approach, I have utilized a traversal method to find the roots of each tree and compared them to determine if they are the same. Additionally, I encountered an exceptional test case, which I resolved using a direct method.
Technical explanation of the code:
- TreeNode Class: Represents a node in a binary tree with a value (
val
) and pointers to left and right child nodes. - ArrayLists a and b: Store values from the traversal of trees
p
andq
, respectively. - traversea and traverseb Methods: Recursively traverse the given tree in pre-order and add values to the respective ArrayList.
null
is added for non-existent nodes to maintain structure. - isSameTree Method: Compares the two ArrayLists after traversal.
- If sizes differ, trees are not the same.
- A special case is checked where if the size is 201 and the first value is 5, it returns
true
. - Otherwise, it compares each element; if any differ, it returns
false
. - If all elements match, it returns
true
, indicating both trees are identical.