System.out.println(ancestor.data)
inside LCA()
method is throwing NPE even though my recursion findlca()
is setting ancestor
value to a node with value 4. I can see this from using debug pointers. Once I come outside my recursion ancestor
field is set to null. Object reference shouldn't change, right?
public class LCA {
static class Node {
int data;
Node left;
Node right;
Node(int data){
this.data =data;
}
}
public static Node lca(Node root, int v1, int v2) {
Node ancestor = null;
findlca(root, v1, v2, ancestor);
System.out.println(ancestor.data);
return ancestor;
}
public static boolean findlca(Node node, int v1, int v2, Node ancestor){
if(node==null){
return false;
}
boolean nodeMatch = false;
if(node.data==v1 || node.data==v2){
nodeMatch = true;
}
boolean leftMatch = findlca(node.left, v1, v2, ancestor);
boolean rightMatch = findlca(node.right, v1, v2, ancestor);
if((leftMatch && rightMatch) || (leftMatch && nodeMatch) || (rightMatch && nodeMatch)){
ancestor = node;
}
return leftMatch || nodeMatch || rightMatch;
}
public static void main(String[] args) {
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(7);
root.left.left = new Node(1);
root.left.right = new Node(3);
root.right.left = new Node(6);
Node ancestor = lca(root, 1, 7);
System.out.println(ancestor.data);
}
}