GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Find the smallest non-negative integer not contained in a binary tree

Write an algorithm (Java code) that, given a binary tree whose nodes contain non-negative integers, determine in time / linear space the smallest non-negative integer that is not contained in the tree and return it.

Example:

with 0 1 2 3 return 4.

with 1 2 3 4 return 0.

with 1 2 5 6 return 3.

with 6 1 5 2 return 3.

My code (Works but is not efficient) is:

public static <E> int minIntNotContains(BinTree<Nodo<Integer>> node) {
    List<Integer> a=new ArrayList<Integer>();
    int min=minIntNotContains(node,a);
    return min;
}

public static <E> int minIntNotContainsRic(BinTree<Nodo<Integer>> node,List<Integer> a) {
    int min= node.getValue().getValue();
    a.add(node.getValue().getValue());
    if(node.getLeftSubtree() != null) {
        min = Math.min(min, minIntNotContainsRic(node.getLeftSubtree(),a));
    }
    if(node.getRightSubtree() != null) {
        min = Math.min(min, minIntNotContainsRic(node.getRightSubtree(),a));
    }
    if (min>0) return 0;  
    else{
        for (int i=0;i<a.size();i++){
            if (!a.contains(i+1)){
                return i+1;
            }
        }
        return min;
    }           
}

how can I solve the problem in O(n)?

Thanks

asked Sep 13, 2016 by anonymous

1 Answer

Error in the text: with 1 2 5 6 return 0.

With 0 1 2 5 6 return 3.

answered Sep 15, 2016 by anonymous
...