一刷 05/2022
Version #1 Recursion
Time O(N)
Space O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
if (root == null || nodes == null) {
return null;
}
Set<Integer> set = new HashSet<>();
for (TreeNode node : nodes) {
set.add(node.val);
}
TreeNode[] result = new TreeNode[1];
countTarget(root, set, result);
return result[0];
}
private int countTarget(TreeNode node, Set<Integer> set, TreeNode[] result) {
if (node == null) {
return 0;
}
int targetSize = set.size();
int left = countTarget(node.left, set, result);
if (left == targetSize) {
return left;
}
int right = countTarget(node.right, set, result);
if (right == targetSize) {
return right;
}
int count = left + right;
if (set.contains(node.val)) {
count++;
}
if (count == targetSize) {
result[0] = node;
}
return count;
}
}
No comments:
Post a Comment