LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV

Question

Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree’s nodes are unique.

Extending the definition of LCA on Wikipedia: “The lowest common ancestor of n nodes p1, p2, …, pn in a binary tree T is the lowest node that has every pi as a descendant (where we allow a node to be a descendant of itself) for every valid i“. A descendant of a node x is a node y that is on the path from node x to some leaf node.

Example 1:

img

1
2
3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
Output: 2
Explanation: The lowest common ancestor of nodes 4 and 7 is node 2.

Example 2:

img

1
2
3
Input: root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [1]
Output: 1
Explanation: The lowest common ancestor of a single node is the node itself.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • All nodes[i] will exist in the tree.
  • All nodes[i] are distinct.

Source: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private TreeNode lca = null;

// return the number of target nodes in the tree of root
// separate lca information and target occurrence information
private int dfs(TreeNode root, Set<TreeNode> set) {
if (root == null) {
return 0;
}

int count = 0;
if (set.contains(root)) {
count++;
}
count += dfs(root.left, set);
count += dfs(root.right, set);

// only set lca once when encountering the lowest common ancestor
if (count == set.size() && lca == null) {
lca = root;
}
return count;
}

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
lca = null;
Set<TreeNode> nodeSet = new HashSet<>(Arrays.asList(nodes));
dfs(root, nodeSet);
return lca;
}
Author

Weihao Ye

Posted on

2022-03-09

Updated on

2022-03-10

Licensed under