LeetCode 236: Lowest Common Ancestor of a Binary Tree

Problem Description

Explanation:

To find the lowest common ancestor (LCA) of two nodes in a binary tree, we can use a recursive approach starting from the root. The idea is to recursively search for the nodes p and q in the left and right subtrees. If both nodes are found in separate subtrees, then the current node is the LCA. If both nodes are found in the same subtree, we continue the search in that subtree.

Algorithm:

  1. If the current node is null or equal to either p or q, return the current node.
  2. Recursively search for p and q in the left subtree.
  3. Recursively search for p and q in the right subtree.
  4. If both p and q are found in separate subtrees, return the current node as LCA.
  5. If both p and q are found in the same subtree, return the LCA from that subtree.

Time Complexity: O(N) - where N is the number of nodes in the tree. Space Complexity: O(N) - recursive stack space.

:

Solutions

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

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;
    return left != null ? left : right;
}

Loading editor...