Chris
Chris

Reputation: 2284

Get Elements from tree at given level

I would like to get all integer keys at a given depth/level of a tree.

The solution I tried looks like this:

public LinkedList<Integer> keysAtDepth(int depth) {
    return getGivenLevel(depth, root);
}

private  LinkedList<Integer> getGivenLevel(int depth, Node root) {
     LinkedList<Integer> list = new  LinkedList<Integer>();

     if (root == null) {
        return list;
    }

    if (depth == 1) {
        System.out.println(root.key);
        list.add(root.key);
    } else if (depth > 1 ) {
        getGivenLevel(depth-1, root.left); 
        getGivenLevel(depth-1, root.right);
    }

    return list;
}

But this is returning me an empty list. The print works just fine, but how can I make it work so I get the keys inside my list?

Upvotes: 0

Views: 137

Answers (2)

As modifying arguments is not a good practice in Java, the minimial side-effect solucion should replace this two lines:

   getGivenLevel(depth-1, root.left); 
   getGivenLevel(depth-1, root.right);

with:

   list.addAll(getGivenLevel(depth-1, root.left)); 
   list.addAll(getGivenLevel(depth-1, root.right));

Upvotes: 1

Karthik Chennupati
Karthik Chennupati

Reputation: 365

The problem with your code is that list is being created every time the function is called and the recursive calls are not adding values to the existing list, but are creating a new list every time. Place the statement LinkedList<Integer> list = new LinkedList<Integer>(); outside the function and your code will work as expected or you can even pass a list reference to the function and add values to that!

Upvotes: 0

Related Questions