MrainW's Home

All things come to those who wait!

0%

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.

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

Solution

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
Set<Integer> set = new HashSet<>();
for (TreeNode t : nodes) set.add(t.val);
return dfs(root, set);
}
private TreeNode dfs(TreeNode root, Set<Integer> set){
if (root == null) return null;
if (set.contains(root.val)) return root;
TreeNode left = dfs(root.left, set);
TreeNode right = dfs(root. right, set);
if (left != null && right != null) return root;
if (left != null) return left;
if (right != null) return right;
return null;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels