#Same Tree LeetCode
20 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @fathom meteor! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
class Solution {
List<Integer> treeElements1 = new ArrayList<>();
List<Integer> treeElements2 = new ArrayList<>();
public boolean isSameTree(TreeNode p, TreeNode q) {
inOrderTraversal(p, treeElements1);
inOrderTraversal(q, treeElements2);
System.out.println("tree 1");
printList(treeElements1);
System.out.println("tree 2");
printList(treeElements2);
if (treeElements1.equals(treeElements2))
return true;
else
return false;
}
public static void printList(List<Integer> list) {
for (Integer element : list) {
System.out.println(element);
}
}
public void inOrderTraversal(TreeNode root, List<Integer> list) {
if (root != null) {
if (root.left != null) {
inOrderTraversal(root.left, list);
}
list.add(root.val);
if (root.right != null) {
inOrderTraversal(root.right, list);
}
}
if(root = null){
}
}
}
Failing test case
You're flattening the trees into Lists, then comparing the Lists
It could work if you ensured the List you flatten to were canonically representing the trees, but you don't. You produce the same list with a missing left node and a missing right node.
yah how to canonically represent the tree?
You could do it the same as they do in the input part
Here when there is a missing node in the middle they insert null
yah I tried that then also it generated the same tree
The same list you mean?
yah it turned out a same list
That's not an attempt to add nulls. You just modified where you insert the root
alright I figured it out
public void inOrderTraversal(TreeNode root, List<Integer> list) {
if (root != null) {
if (root.left != null) {
inOrderTraversal(root.left, list);
} else {
list.add(null);
}
list.add(root.val);
if (root.right != null) {
inOrderTraversal(root.right, list);
} else {
list.add(null);
}
inOrderTraversal(root.right, list);
}
}
I just noticed your list is not like the one they put in input box. I'm not sure it will be canonical this way
is the better approach?
This reaches till the end of the leaf node of one of the tree right
Then it check if the values are null, one is not null or no even
I mean, it's the most direct approach. Trees are recursive structures, so it checks recursively and directly.