@12GitTho10
Question is asking for longest path which has same node value
combine both left and right
so the path is
leftmost 4 -> middle 4 -> right down 4
as all node values is 4 we have to consider all
Hope this will help.
@12GitTho10
Question is asking for longest path which has same node value
combine both left and right
so the path is
leftmost 4 -> middle 4 -> right down 4
as all node values is 4 we have to consider all
Hope this will help.
@cheesewraps
Count number of edges and not number of nodes. 2 is correct answer here.
@lupinekaupz
Thanks.
Actually we can use Math.min to decide on left or right path.
second last line, why do you need + res at the end?
it looks like you are adding emty string at the end ? but in a loop res will change, so in second iteration you will not get empty string? please let me know if you need it for specific reason.
for (String dir : stack) res = "/" + dir + res;
@mikealive
I think this will work if its BST. did you think of any case where this code will fail ?
import java.util.*;
public class DistanceBetweenBSTNode{
public int distance(TreeNode root, TreeNode node1,TreeNode node2){
if(root == null || node1 == node2)
return 0;
if(root.val >= node1.val && root.val <= node2.val)
return distance(root,node1) + distance(root,node2);
else if(root.val < node1.val && root.val < node2.val)
return distance(root.right,node1,node2);
else{
return distance(root.left,node1,node2);
}
}
public int distance(TreeNode root, TreeNode node1){
if(root == node1)
return 0;
if(root.val < node1.val){
return 1+ distance(root.right,node1);
}
else{
return 1+ distance(root.left,node1);
}
}
public static void main(String[] args){
DistanceBetweenBSTNode dbb = new DistanceBetweenBSTNode();
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(10);
root.right.right = new TreeNode(11);
root.right.left = new TreeNode(8);
//dbb.inorder(root);
System.out.println(dbb.distance(root,root,root.right.right));
}
}