I found this solution on Leetcode while trying to solve this problem:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Everyone on Leetcode seems to take for granted how this works. But I don't get it. What is going on here and what algorithm is this using to find the LCA of the binary tree?
public TreeNode lowestCommonAncestorBinaryTree(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) {
return null;
}
if(root==p) {
return p;
}
if(root==q) {
return q;
}
TreeNode left = lowestCommonAncestorBinaryTree(root.left, p, q);
TreeNode right = lowestCommonAncestorBinaryTree(root.right, p, q);
if (left != null && right != null) {
return root;
}
if(left!=null && right==null) {
return left;
}
if(right!=null && left==null) {
return right;
}
return null;
}