Taro Logo

Lowest Common Ancestor of a Binary Tree

#10 Most AskedMedium
0 views
Topics:
TreesRecursion

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).”

Example 1:

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.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the tree.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are `p` and `q` guaranteed to be present within the given binary tree, or is it possible that one or both nodes do not exist in the tree?
  2. Can the tree contain duplicate values, or are all node values guaranteed to be unique?
  3. What should the function return if either `p` or `q` is not found in the tree?
  4. Is the binary tree guaranteed to be valid and non-empty (i.e., root is not null), or could I receive an empty tree as input?
  5. Can a node be considered a descendant of itself for this definition of LCA, or must `p` and `q` be strictly distinct nodes in separate subtrees?

Brute Force Solution

Approach

Imagine you are trying to find the closest shared meeting point for two people in a massive family tree. The brute force approach involves looking at every single person in the tree one by one to see which ones are related to both targets.

Here's how the algorithm would work step-by-step:

  1. Pick the first person in the family tree.
  2. Check if the first person is one of your two targets, or if both targets are hidden somewhere among their descendants.
  3. If that person does not satisfy the condition, move on to the next person in the tree and repeat the check.
  4. Keep going through every single person in the entire family tree, one by one.
  5. As you check each person, remember the ones that have both targets somewhere in their family branch.
  6. Out of all the people who passed the test, pick the one that is lowest down in the tree, meaning they are the most recent shared family member.

Code Implementation

def lowest_common_ancestor(root_node, target_one, target_two):
    # We traverse every node to evaluate each one as a potential ancestor candidate
    all_tree_nodes = []
    
    def collect_nodes(current_node):
        if current_node:
            all_tree_nodes.append(current_node)
            collect_nodes(current_node.left)
            collect_nodes(current_node.right)

    collect_nodes(root_node)

    def covers_targets(ancestor_node, node_one, node_two):
        if not ancestor_node:
            return False
        
        def contains_node(subtree_root, target_node):
            if not subtree_root:
                return False
            if subtree_root == target_node:
                return True
            return contains_node(subtree_root.left, target_node) or contains_node(subtree_root.right, target_node)

        return contains_node(ancestor_node, node_one) and contains_node(ancestor_node, node_two)

    # We track valid ancestors to find the deepest one among all qualified candidates
    valid_ancestors = []

    for candidate_node in all_tree_nodes:
        if covers_targets(candidate_node, target_one, target_two):
            valid_ancestors.append(candidate_node)

    def get_node_depth(current_root, target_node, current_depth):
        if not current_root:
            return -1
        if current_root == target_node:
            return current_depth
        
        left_search_depth = get_node_depth(current_root.left, target_node, current_depth + 1)
        if left_search_depth != -1:
            return left_search_depth
        
        return get_node_depth(current_root.right, target_node, current_depth + 1)

    deepest_ancestor_node = None
    maximum_depth_value = -1

    # We compare depths to ensure we select the lowest common ancestor in the tree
    for valid_candidate in valid_ancestors:
        candidate_depth = get_node_depth(root_node, valid_candidate, 0)
        if candidate_depth > maximum_depth_value:
            maximum_depth_value = candidate_depth
            deepest_ancestor_node = valid_candidate

    return deepest_ancestor_node

Big(O) Analysis

Time Complexity
O(n²) – For each of the n people in the family tree, we must check their entire branch of descendants to see if both targets are present. In the worst-case scenario of a skewed tree, we visit every node and perform a sub-search that takes up to O(n) operations for each visit. This leads to approximately n * n operations overall. Simplifying this total by dropping constants gives a final Big O time complexity of O(n²).
Space Complexity
O(H) – The space complexity is driven entirely by the recursion stack used to traverse the family tree, where H represents the height of the tree. In the worst-case scenario of a completely unbalanced tree, such as a linked list, the depth reaches N, requiring O(N) extra space. For a well-balanced tree, the maximum depth of recursive calls is proportional to log N, resulting in O(log N) auxiliary space. These stack frames store the active path of ancestors being evaluated as the algorithm checks each person's descendants. Therefore, the memory consumed scales with the maximum depth of the tree rather than the total number of nodes.

Optimal Solution

Approach

To find the lowest common ancestor in a family tree of nodes, we can dive deep down to the bottom and let each branch report back what it discovers. By asking our children if they have spotted either of our target nodes, we can magically figure out the meeting point on the way back up.

Here's how the algorithm would work step-by-step:

  1. Begin by standing at the very top of the tree and looking for a path that leads downward to either of the two target nodes.
  2. Send explorers down both the left and right paths to search for the targets.
  3. When an explorer reaches a dead end or finds one of the target nodes, they report their findings back to the person who sent them.
  4. As reports travel upward, each parent listens to what came back from their left side and their right side.
  5. If a parent receives a positive report from both the left branch and the right branch, it means that parent is the exact meeting point where the two paths converge, making them the lowest common ancestor.
  6. If a parent only receives a positive report from one side, they simply pass that finding upward, trusting that the higher levels will sort it out.
  7. Eventually, the final answer bubbles all the way up to the top, giving us our winning node without needing to search blindly.

Code Implementation

class Solution:
    def lowestCommonAncestor(self, root_node, target_node_p, target_node_q):
        # Base case: if we hit a dead end or find a target, report this node upward immediately.
        if root_node is None or root_node == target_node_p or root_node == target_node_q:
            return root_node

        left_branch_result = self.lowestCommonAncestor(root_node.left, target_node_p, target_node_q)

        right_branch_result = self.lowestCommonAncestor(root_node.right, target_node_p, target_node_q)

        # If both sides found something, this current node is the convergence point and LCA.
        if left_branch_result and right_branch_result:
            return root_node

        # If only one side found a target, pass that finding upward along the chain.
        return left_branch_result if left_branch_result else right_branch_result

Big(O) Analysis

Time Complexity
O(n) – In this recursive depth-first search approach, the input size n represents the total number of nodes in the binary tree. Every single node is visited and explored exactly once by our recursive function as it traverses both the left and right branches from the top down to the bottom. As the reports bubble back up, a constant amount of work is performed at each node to check its children. This means the total number of operations grows in direct proportion to n, simplifying the overall time complexity to O(n).
Space Complexity
O(h) – The auxiliary space is driven entirely by the recursion stack frames as explorers dive deep down to the bottom of the tree. In the worst-case scenario, such as a completely unbalanced skewed tree, the recursive calls will add up to a maximum depth of N, where N is the total number of nodes. For a balanced tree, this depth is limited to the height of the tree, which is proportional to log N. Therefore, the memory consumed by the call stack simplifies to O(h) in general, or O(N) in the absolute worst-case linear tree structure.

Edge Cases

One target node is an ancestor of the other target node
How to Handle:
The recursive function naturally returns the ancestor node as soon as it hits it without searching further down.
The binary tree is completely skewed like a linked list
How to Handle:
The recursion depth will equal the height of the tree, reaching up to O(N) frames on the call stack.
The tree consists of only a single node
How to Handle:
The base case will immediately return that single node if it matches one of the targets.
Both target nodes are located in the same subtree of the root
How to Handle:
The root will receive non-null returns from only one side, propagating that side's result all the way up.
The tree has maximum nodes with a balanced depth of log N
How to Handle:
The recursive approach efficiently traverses the tree in O(N) time and O(log N) space due to balanced stack depth.
One or both target nodes do not exist in the tree
How to Handle:
While standard problems guarantee existence, a robust check ensures we return null if a target is missing.
0/13 completed