The main idea of โโmarking the presence of a number in a tree branch is to use a non-zero pointer for the FOUND number and a null pointer for NOTFOUND.
The call column goes back when a number ( p or q ) is found, or when root is null . Later, a clear indication of the absence of the desired number is given.
There are four possible scenarios:
1.) And under one parent.
root / \ Leftsubtree Rightsubtree p/qq/p
In this case, in the code below, the moment will come when it will be done if(left != null && right != null) return root;
2.) One parent of the other.
q/pp/q / OR \ Leftsubtree Rightsubtree p/qq/p
In this case, this will be done if(root == null || root == p || root == q) return root;
3.) Or they are not present in the tree. This condition will be undetected . As shown in case No. 2, the function immediately returns without further movement and looks for its copy in the tree below.
4.) None of them are present in the tree.
The first line if(root == null ... return ; will be executed for each non-existent child. The final result will be null return, since none of the numbers will be found.
Explanation by line.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) return root;