int numKey;
char charKey;
numKey=keyVal;
}
charKey=keyVal;
}
charKey=keyVal;
left=leftChild;
right=rightChild;
}
LCA lcaObj = new LCA();
lcaObj.val1=val1;
lcaObj.val2=val2;
return findLCA_internal(root,lcaObj);
}
if(root==null) return null;
if(lcaObj.val1Found && lcaObj.val2Found){
// both values are found at previous level so do nothing more
return null;
}else{
boolean val1FlagBefore = lcaObj.val1Found;
boolean val2FlagBefore = lcaObj.val2Found;
if(!lcaObj.val1Found && root.numKey==lcaObj.val1){
lcaObj.val1Found=true;
}if(!lcaObj.val2Found && root.numKey==lcaObj.val2){
lcaObj.val2Found=true;
}
TreeNode lcaPresentInLeftTree
= findLCA_internal
(root.
left,lcaObj
); if(lcaPresentInLeftTree !=null){
return lcaPresentInLeftTree;
}else{
TreeNode lcaPresentInRightTree
= findLCA_internal
(root.
right,lcaObj
); if(lcaPresentInRightTree!=null) {
return lcaPresentInRightTree;
}else{
// LCA is not presnt in left tree nor it is present in right tree. So check if this node itself if LCA
// before this node was checked ;val1 flag was false and afterwards it is true.
// ALSO
// before this node was checked; val2 flag was false and and afterwards it is true.
// This root is the LCA
if(!val1FlagBefore && lcaObj.val1Found && !val2FlagBefore && lcaObj.val2Found){
return root;
}else{
// So either or both of keys are not present in this tree
return null;
}
}
}
}
}
public static void main
(String[] args
) { /*
10
/ \
20 30
/ \
40 50
*/
lcaNode = findLCA(root, 50, 40);
System.
out.
println("findLCA(root, 50, 40)" + lcaNode.
numKey ); lcaNode = findLCA(root, 30, 40);
System.
out.
println("findLCA(root, 30, 40)"+ lcaNode.
numKey ); lcaNode = findLCA(root, 30, 20);
System.
out.
println("findLCA(root, 30, 20)"+ lcaNode.
numKey ); lcaNode = findLCA(root, 50, 20);
System.
out.
println("findLCA(root, 50, 20)"+ lcaNode.
numKey );
}
}
class LCA{
int val1,val2;
boolean val1Found=false;
boolean val2Found=false;
}
Y2xhc3MgVHJlZU5vZGUgewppbnQgbnVtS2V5OwpjaGFyIGNoYXJLZXk7CnB1Y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