In your approach, you seem to assume that cousins can have only 1 different parent. The more we go deeper, the more the different parents for a particular find
node or you can say the more the cousins. Also, if(root.left == find && root.right == find){
doesn't make sense since there can't be 2 same nodes in the tree, especially with find
.
In your printCousins
, you will need to find the level of the find
node and then collect all it's cousins by passing it to siblings
method.
public static ArrayList<Integer> printCousins(Node root, Node find){
//code here
ArrayList<Integer> arr = new ArrayList<>();
int level = findLevel(root, find, 0);
if(level == -1){
arr.add(-1);
return arr;
}
siblings(root, find, arr, 0, level);
if(arr.isEmpty()){
arr.add(-1);
}
return arr;
}
Since you use depth first search technique, you can find the level of the find
node first like below:
static int findLevel(Node root, Node find, int level){
if(root == null) return -1;
if(root == find) return level;
int l = findLevel(root.left, find, level + 1);
if(l == -1) l = findLevel(root.right, find, level + 1);// only go to the right side of the node if not found on the left part
return l;
}
In siblings
, you will add all those nodes to arr
that are located at level
with a careful check of the parent not having find
as one of their kids thereby ensuring different parents same level requirement.
static void siblings(Node root, Node find, ArrayList<Integer> arr, int curr_level, int level){
if(root == null || curr_level > level || root == find) return;
if(curr_level + 1 == level){
if(root.left == find || root.right == find) return; // making sure either of the kids isn't 'find'
}
if(curr_level == level){
arr.add(root.val);
return;
}
siblings(root.left, find, arr, curr_level + 1, level);
siblings(root.right, find, arr, curr_level + 1, level);
}