Skip to content

Latest commit

 

History

History
76 lines (54 loc) · 2.57 KB

0236.md

File metadata and controls

76 lines (54 loc) · 2.57 KB

Level: Medium

Topic: Tree Binary Tree Depth First Search

Similar Problem:

Question

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Intuition

Recursive:

  • Base Case:
    1. if reaches the null nodes, return null
    2. if find the node p or q, return root

Then,

  • Traverse left and right until finds a path containing p or q
  • if found a path contains p or q, return root back up to the ancestor
  • when returned back up, check for the path at current node (it might be the ancestor of p and q)
  • there are 4 cases
    1. p and q found -> means already found the lowest common ancestor (the first time this condition is true, it's the LCA since it's a bottom-up process)
    2. p and q not found both null -> not been found yet
    3. p found and q = null
    4. p = null and q found -> these two cases, it might be 2 situation, one is a descendant of the other or we haven't see the lowest common ancestor yet so we have to return the found node back up.

Code

Time: O(n)
Space: O(n)

Recursive

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    // base case
    if (root == null)
        return null;
    if (root == p || root == q)
        return root;

    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);


    // if both p and q are found, it's lowest common ancestor
    if (left != null && right != null)
        return root;

    // if either are not found, haven't found a path to p or q
    if (left == null && right == null)
        return null;

    // either one is found or there is impossible that one is not in the subtree of another
    return left == null ? right : left;
}