LCA by inorder and postorder traversal was easily implemented and understood by me.
But, there is a recursive bottom-up approach.
I had a look at the code online, and I didn't understand one line:
Here is the code:
public Node lowestCommonAncestor(int val1, int val2,Node root){
if(root == null){
return null;
}
if(root.data == val1 || root.data == val2){
return root;
}
Node left = lowestCommonAncestor(val1, val2, root.left);
Node right = lowestCommonAncestor(val1, val2, root.right);
if(left != null && right != null){
return root;
}
return left != null ? left : right;
}
val1 and val2 are two node's value whose LCA needs to be found.
The last line is where I am stuck on.
return left != null ? left : right;
Can some one explain this?
Thank you.