Skip to content

Commit b8a6ad8

Browse files
committed
Add 1676_Lowest_Common_Ancestor_of_a_Binary_Tree_IV.java
1 parent 22fd2a0 commit b8a6ad8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
3+
Set<TreeNode> s = new HashSet<>();
4+
5+
for (TreeNode n : nodes) {
6+
s.add(n);
7+
}
8+
9+
return helper(root, s);
10+
}
11+
12+
private TreeNode helper(TreeNode root, Set<TreeNode> s) {
13+
if (root == null) {
14+
return null;
15+
}
16+
17+
if (s.contains(root)) {
18+
return root;
19+
}
20+
21+
TreeNode left = helper(root.left, s);
22+
TreeNode right = helper(root.right, s);
23+
24+
if (left == null) {
25+
return right;
26+
}
27+
if (right == null) {
28+
return left;
29+
}
30+
31+
return root;
32+
}
33+
}

0 commit comments

Comments
 (0)