1676. Lowest Common Ancestor of a Binary Tree IV
Previous1650. Lowest Common Ancestor of a Binary Tree IIINext1689. Partitioning Into Minimum Number Of Deci-Binary Numbers
Last updated
Last updated
/**
* Time complexity : O(N)
* Space complexity : O(N)
*/
class Solution {
private Set<TreeNode> nodesSet;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) {
nodesSet = new HashSet(Arrays.asList(nodes));
return lcaHelper(root);
}
private TreeNode lcaHelper(TreeNode root) {
if(root == null || nodesSet.contains(root)) {
return root;
}
TreeNode left = lcaHelper(root.left);
TreeNode right = lcaHelper(root.right);
if(left != null && right != null) {
return root;
}
return (left != null)? left: right;
}
}