Untitled
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) { return root; // Base case: found a node or reached the end } // Recursively find LCA in left and right subtrees TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; // If both subtrees return non-null, root is LCA } return (left != null) ? left : right; // Return non-null subtree }
Leave a Comment