public LinkedList<Integer> findAncestors(TreeNode root, TreeNode target){
LinkedList<Integer> ancestors = new LinkedList<>();
findAncestorsRec(root, target, ancestors);
return ancestors;
}
public boolean findAncestorsRec(TreeNode root, TreeNode target, LinkedList<Integer> ancestors){
if(root == null) return false;
//TARGET FOUND IN LEFT CHILD
if(root.left != null){
if(root.left.val == target.val){
ancestors.add(root.val);
return true;
}
}
//TARGET FOUND IN RIGHT CHILD
if(root.right != null){
if(root.right.val == target.val){
ancestors.add(root.val);
return true;
}
}
//Search in both side and add noce is ancestor
boolean foundLeft = false;
boolean foundRight = false;
//if we either see that we found the node in our
//left or right childs it means current node is an ancestor
//we add our current node to
if(root.left != null){
if(findAncestorsRec(root.left, target, ancestors)) foundLeft = true;
}
if(root.right != null){
if(findAncestorsRec(root.right, target, ancestors)) foundRight = true;
}
if(foundLeft || foundRight){
//add node as ancestor and return
ancestors.add(root.val);
return true;
}
return false;
}