Java Binary Tree Program · OT77
Lowest Common Ancestor in a Binary Tree in Java
Search both subtrees. If p is found on one side and q on the other, the current node is where their paths split, which is the lowest common ancestor.
Problem Statement
Given a binary tree and two of its nodes, p and q, return their lowest common ancestor: the deepest node that has both p and q in its subtree.
A node counts as a descendant of itself, so if p is an ancestor of q, the answer is p. The tree is not assumed to be a BST.
Input/Output Examples
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7], p = 4, q = 7Output6Explanation: 4 and 7 are the children of 6.same tree, p = 1, q = 7Output3Explanation: 1 is in 3's left subtree and 7 in its right subtree.same tree, p = 6, q = 4Output6Explanation: 6 is an ancestor of 4.Visual Explanation
- At 8foundleft: 3right: nullboth are on the left
- At 3foundleft: 1right: 6p left, q right
- Donepaths split at 3LCA = 3
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7]: at node 3, one target is in each subtree, so 3 is returned and passed up unchanged.Each recursive call returns p, q, the LCA, or null. A node that receives non-null results from both sides is the LCA; otherwise it passes up whichever side found something.
Approaches
The recursive approach finds the answer in one traversal. The parent-map approach records ancestors explicitly.
Approach 1: Single Recursive Pass (Recommended)
Idea: return the node itself if it is p or q; otherwise combine the results from the left and right subtrees.
- Return the node if it is null, p or q.
- Recurse into both subtrees.
- If both sides return a node, this node is the LCA.
- Otherwise return the non-null side.
Time: O(n) · Space: O(h).
Approach 2: Parent Map and Ancestor Set
Idea: record every node's parent, put all of p's ancestors in a set, then climb from q until reaching one of them.
- Traverse the tree and store each node's parent.
- Walk from p to the root, adding every node to a set.
- Walk from q upwards until the current node is in the set.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Single Recursive Pass (Recommended)
Compares node references, so the values do not even need to be unique.
public class LcaRecursive {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// If p and q are found in different subtrees, this node is their lowest common ancestor
static TreeNode lca(TreeNode node, TreeNode p, TreeNode q) {
if (node == null || node == p || node == q) {
return node;
}
TreeNode left = lca(node.left, p, q);
TreeNode right = lca(node.right, p, q);
if (left != null && right != null) {
return node;
}
return left != null ? left : right;
}
static TreeNode find(TreeNode n, int v) {
if (n == null || n.val == v) {
return n;
}
TreeNode left = find(n.left, v);
return left != null ? left : find(n.right, v);
}
public static void main(String[] args) {
TreeNode root = build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7);
int[][] queries = {{4, 7}, {1, 7}, {4, 14}, {6, 4}};
for (int[] q : queries) {
System.out.println("p=" + q[0] + ", q=" + q[1] + " -> " + lca(root, find(root, q[0]), find(root, q[1])).val);
}
}
}
p=4, q=7 -> 6 p=1, q=7 -> 3 p=4, q=14 -> 8 p=6, q=4 -> 6
Time complexity: O(n) · Space complexity: O(h).
Approach 2: Parent Map and Ancestor Set
Useful when many LCA queries are asked on the same tree: the parent map is built once.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LcaParents {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// Record every node's parent, collect p's ancestors, then climb from q until one is shared
static TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
Map<TreeNode, TreeNode> parent = new HashMap<>();
parent.put(root, null);
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode n = stack.pop();
if (n.left != null) { parent.put(n.left, n); stack.push(n.left); }
if (n.right != null) { parent.put(n.right, n); stack.push(n.right); }
}
Set<TreeNode> ancestors = new HashSet<>();
for (TreeNode n = p; n != null; n = parent.get(n)) {
ancestors.add(n);
}
TreeNode n = q;
while (!ancestors.contains(n)) {
n = parent.get(n);
}
return n;
}
static TreeNode find(TreeNode n, int v) {
if (n == null || n.val == v) {
return n;
}
TreeNode left = find(n.left, v);
return left != null ? left : find(n.right, v);
}
public static void main(String[] args) {
TreeNode root = build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7);
int[][] queries = {{4, 7}, {1, 7}, {4, 14}, {6, 4}};
for (int[] q : queries) {
System.out.println("p=" + q[0] + ", q=" + q[1] + " -> " + lca(root, find(root, q[0]), find(root, q[1])).val);
}
}
}
p=4, q=7 -> 6 p=1, q=7 -> 3 p=4, q=14 -> 8 p=6, q=4 -> 6
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Single Recursive Pass | O(n) | O(h) |
| Parent Map and Ancestor Set | O(n) | O(n) |
Here n is the number of nodes and h the height. Both approaches may visit every node; the parent map stores one entry per node.
Interview Tips and Recommended Approach
- Handle the ancestor case. Returning a node as soon as it equals p or q covers it.
- Use the BST shortcut when possible. In a BST, compare values and go left or right only.
- Ask whether p and q are guaranteed to exist; if not, verify both were found.
- Know the uses: distances between nodes and organisation-chart queries.
Recommended Approach: Single Recursive Pass
Why: it finds the answer in a single traversal with no extra data structures, using a short and elegant recursion.