You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Since there are conditions for this problem: all values in the tree and given nodes are unique, we could simply use a HashSet to track the number of nodes we've found so far during the traversal.
*/
TreeNode lca;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
Set<Integer> target = new HashSet<>();
for (TreeNode node : nodes) {
target.add(node.val);
}
dfs(root, target);
return lca;
}
private int dfs(TreeNode root, Set<Integer> target) {