1676. Lowest Common Ancestor of a Binary Tree IV
this Q is for n nodes:
just like 236 count solution, count == n is the ans
T: O(n)
S: O(n)
class Solution {
TreeNode res = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
dfs(root, nodes);
return res;
}
private int dfs(TreeNode root, TreeNode[] nodes) {
if (root == null) {
return 0;
}
int left = dfs(root.left, nodes);
int right = dfs(root.right, nodes);
int self = 0;
for (TreeNode node : nodes) {
if (node.val == root.val) {
self = 1;
break;
}
}
int count = left + right + self;
if (count == nodes.length && res == null) {
res = root;
}
return count;
}
}use hashset to accelerate speed
Last updated
Was this helpful?