Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trees

Lowest Common Ancestor in a Binary Tree

Medium · Trees · Asked at Amazon, Meta, Microsoft, Google, LinkedIn

All values are distinct and both p and q are in the tree (it is not necessarily a BST). Print the value of their lowest common ancestor — the deepest node that has both as descendants (a node counts as its own descendant).

Input

First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: p q.

Output

The value of the LCA.

Constraints

Recursive: if the node is null, p or q, return it. Otherwise look left and right; if both sides return something, this node is the LCA.

Example 1

Input

11
3 5 1 6 2 0 8 -1 -1 7 4
5 1

Output

3

Example 2

Input

11
3 5 1 6 2 0 8 -1 -1 7 4
5 4

Output

5

Hints

  1. If the current node is p or q, it is the answer for this subtree (the other one is below it or elsewhere).
  2. Ask both subtrees. If both return a node, p and q are on different sides and the current node is the LCA; otherwise pass up whichever side found something.

Approach

lca(n) returns: null if the subtree has neither p nor q; the node p or q if exactly that one is found (or n itself is p/q); the LCA once both are found. At a node, if both recursive calls return non-null, p and q split here — this node is the LCA. Because both values are guaranteed to exist, the root call returns the correct answer.

Complexity: O(n) time · O(h) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *left = nullptr, *right = nullptr;
    Node(long long v) : val(v) {}
};

// Build a tree from level order where -1 means "no node".
Node *readTree() {
    int k;
    cin >> k;
    vector<long long> v(k);
    for (auto &x : v) cin >> x;
    if (k == 0 || v[0] == -1) return nullptr;
    Node *root = new Node(v[0]);
    queue<Node *> q;
    q.push(root);
    int i = 1;
    while (!q.empty() && i < k) {
        Node *cur = q.front();
        q.pop();
        if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
        i++;
        if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
        i++;
    }
    return root;
}

long long p, q;

Node *lca(Node *n) {
    if (!n || n->val == p || n->val == q) return n;
    Node *a = lca(n->left), *b = lca(n->right);
    if (a && b) return n;
    return a ? a : b;
}

int main() {
    Node *root = readTree();
    cin >> p >> q;
    cout << lca(root)->val << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

sys.setrecursionlimit(100000)

class Node:
    def __init__(self, val):
        self.val, self.left, self.right = val, None, None


def build_tree(v):
    """Build a tree from level order where -1 means "no node"."""
    if not v or v[0] == -1:
        return None
    root = Node(v[0])
    q, i = deque([root]), 1
    while q and i < len(v):
        cur = q.popleft()
        if i < len(v) and v[i] != -1:
            cur.left = Node(v[i])
            q.append(cur.left)
        i += 1
        if i < len(v) and v[i] != -1:
            cur.right = Node(v[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]

p, q = rest[0], rest[1]


def lca(n):
    if not n or n.val in (p, q):
        return n
    a, b = lca(n.left), lca(n.right)
    if a and b:
        return n
    return a or b


print(lca(root).val)

Java solution

import java.util.*;

public class Main {
    static class Node {
        long val;
        Node left, right;
        Node(long v) { val = v; }
    }

    // Build a tree from level order where -1 means "no node".
    static Node readTree(Scanner sc) {
        int k = sc.nextInt();
        long[] v = new long[k];
        for (int i = 0; i < k; i++) v[i] = sc.nextLong();
        if (k == 0 || v[0] == -1) return null;
        Node root = new Node(v[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < k) {
            Node cur = q.poll();
            if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
            i++;
            if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
            i++;
        }
        return root;
    }

    static long p, q;

    static Node lca(Node n) {
        if (n == null || n.val == p || n.val == q) return n;
        Node a = lca(n.left), b = lca(n.right);
        if (a != null && b != null) return n;
        return a != null ? a : b;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Node root = readTree(sc);
        p = sc.nextLong();
        q = sc.nextLong();
        System.out.println(lca(root).val);
    }
}

Solve Lowest Common Ancestor in a Binary Tree online · All practice problems