def lca(root,p,q):
if not root or root==p or root==q: return root
left=lca(root.left,p,q)
right=lca(root.right,p,q)
return root if left and right else left or right
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);
return left!=null&&right!=null?root:left!=null?left:right;
}
'left or right' returns first truthy. Java needs ternary chain.
def lca(root,p,q):
if not root or root==p or root==q: return root
left=lca(root.left,p,q)
right=lca(root.right,p,q)
return root if left and right else left or right
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);
return left!=null&&right!=null?root:left!=null?left:right;
}
1. Base case: null or target 2. Recurse both 3. Both found: current is LCA