Lowest Common Ancestor of a Binary Tree IV
还是找LCA, 这次是找n个node的lca
一个个找即可.
/**
* 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) {
Set<TreeNode> set = new HashSet<>();
for(TreeNode n : nodes){
set.add(n);
}
return find(root, set);
}
private TreeNode find(TreeNode root, Set<TreeNode> set) {
if(root == null)
return root;
if(set.contains(root)){
set.remove(root);
return root;
}
TreeNode left = find(root.left, set);
TreeNode right = find(root.right, set);
if(left != null && right != null)
return root;
if(left == null)
return right;
else
return left;
}
}