Practice › Trees
Smallest Subtree with All the Deepest Nodes
Medium · Trees · Asked at Meta, Amazon, Google
All values are distinct. Find the smallest subtree (a node together with all its descendants) that contains all the deepest nodes of the tree, and print the value of its root.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node.
Output
The value of the subtree’s root.
Constraints
- 1 ≤ number of nodes ≤ 10^4
- values are distinct and positive
Post-order: for each node return (height of its subtree, answer node for its subtree). If both children have the same height, the node itself is the answer; otherwise take the answer of the taller child. Equivalently, it is the lowest common ancestor of the deepest leaves.
Example 1
Input
11 3 5 1 6 2 10 8 -1 -1 7 4
Output
2
Example 2
Input
1 1
Output
1
Hints
- For each node, you need the height of its subtree and the answer inside it.
- If both children are equally tall, the deepest nodes are on both sides — the node itself is the answer.
- Otherwise the answer lies in the taller child.
Approach
Process nodes children-first (reversed preorder, no recursion). For a node with child results (hl, al) and (hr, ar) — a missing child has height 0: if hl == hr the node is the answer with height hl + 1; if hl > hr pass up (hl + 1, al); else (hr + 1, ar). The root's answer is the lowest common ancestor of all the deepest nodes.
Complexity: O(n) time · O(n) 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) {}
};
Node *build(const vector<long long> &a) {
if (a.empty() || a[0] == -1) return nullptr;
Node *root = new Node(a[0]);
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
i++;
}
return root;
}
int main() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &v : a) cin >> v;
Node *root = build(a);
vector<Node *> order, st = {root};
while (!st.empty()) {
Node *n = st.back();
st.pop_back();
order.push_back(n);
if (n->left) st.push_back(n->left);
if (n->right) st.push_back(n->right);
}
unordered_map<Node *, pair<int, Node *>> info;
for (int i = (int) order.size() - 1; i >= 0; i--) {
Node *n = order[i];
pair<int, Node *> L = n->left ? info[n->left] : make_pair(0, (Node *) nullptr);
pair<int, Node *> R = n->right ? info[n->right] : make_pair(0, (Node *) nullptr);
if (L.first == R.first) info[n] = {L.first + 1, n};
else if (L.first > R.first) info[n] = {L.first + 1, L.second};
else info[n] = {R.first + 1, R.second};
}
cout << info[root].second->val << "\n";
return 0;
}Python solution
import sys
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(a):
if not a or a[0] == -1:
return None
root = Node(a[0])
q = deque([root])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
cur.left = Node(a[i])
q.append(cur.left)
i += 1
if i < len(a) and a[i] != -1:
cur.right = Node(a[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
root = build(data[1 : 1 + data[0]])
order, stack = [], [root]
while stack:
node = stack.pop()
order.append(node)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
info = {}
for node in reversed(order):
hl, al = info[id(node.left)] if node.left else (0, None)
hr, ar = info[id(node.right)] if node.right else (0, None)
if hl == hr:
info[id(node)] = (hl + 1, node)
elif hl > hr:
info[id(node)] = (hl + 1, al)
else:
info[id(node)] = (hr + 1, ar)
print(info[id(root)][1].val)Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
static Node build(long[] a) {
if (a.length == 0 || a[0] == -1) return null;
Node root = new Node(a[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < a.length) {
Node cur = q.poll();
if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
i++;
if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
i++;
}
return root;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int k = (int) in.nval;
long[] a = new long[k];
for (int i = 0; i < k; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
Node root = build(a);
ArrayList<Node> order = new ArrayList<>();
ArrayDeque<Node> st = new ArrayDeque<>();
st.push(root);
while (!st.isEmpty()) {
Node n = st.pop();
order.add(n);
if (n.left != null) st.push(n.left);
if (n.right != null) st.push(n.right);
}
HashMap<Node, Integer> height = new HashMap<>();
HashMap<Node, Node> ans = new HashMap<>();
for (int i = order.size() - 1; i >= 0; i--) {
Node n = order.get(i);
int hl = n.left != null ? height.get(n.left) : 0, hr = n.right != null ? height.get(n.right) : 0;
if (hl == hr) ans.put(n, n);
else if (hl > hr) ans.put(n, ans.get(n.left));
else ans.put(n, ans.get(n.right));
height.put(n, Math.max(hl, hr) + 1);
}
System.out.println(ans.get(root).val);
}
}Solve Smallest Subtree with All the Deepest Nodes online · All practice problems