AlgoMaster Logo

Lowest Common Ancestor of a Binary Tree

tree=[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4],p=5,q=1
1class Solution {
2    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3        // Base case: null or found p/q
4        if (root == null || root == p || root == q) {
5            return root;
6        }
7
8        // Search in left subtree
9        TreeNode left = lowestCommonAncestor(root.left, p, q);
10
11        // Search in right subtree
12        TreeNode right = lowestCommonAncestor(root.right, p, q);
13
14        // If both return non-null, current node is LCA
15        if (left != null && right != null) {
16            return root;
17        }
18
19        // Return whichever is non-null
20        return left != null ? left : right;
21    }
22}
0 / 10
351620874