views:

132

answers:

4

I'm trying to remove all of the leaves. I know that leaves have no children, this is what I have so far.

 public void removeLeaves(BinaryTree n){  

    if (n.left == null && n.right == null){

        n = null;

    }

    if (n.left != null)

        removeLeaves(n.left);

    if (n.right != null)

        removeLeaves(n.right);

}
+2  A: 

Instead of n = null, it should be:

if(n.parent != null)
  {
    if(n.parent.left == n)
    {
      n.parent.left = null;
    } 
    else if(n.parent.right == n)
    {
      n.parent.right == null);
    }
  }
Matthew Flaschen
This will fail with a `NullPointerException` if the root is a leaf itself.
Heinzi
What I'm doing is a data structure, meaning that I built the BinaryTree class and in this case the parent would be n.
flopex
Thanks, Heinzi. Fixed.
Matthew Flaschen
+4  A: 

n = null; won't help you, since n is just a local variable of your function. Instead, you'd need to set n.left = null; or n.right = null; on the parent.

I won't give you a complete solution, since this smells a lot like homework, but you could, for example, add a return value to your function to indicate whether the node in question is a leaf or not and take appropriate actions in the parent (after the call to removeLeaves).

Heinzi
+1  A: 

Since Java passes references by values n = null; simply does not work. With this line n was pointing to the leaf and now points to nothing. So you aren't actually removing it from the parent, you are just rerouting a dummy local reference. For the solution do what Matthew suggested.

Petar Minchev
+5  A: 

It's much easier if you break this down like this:

public void removeLeaves(BinaryTree n){
  if (n.left != null) {
    if (n.left.isLeaf()) {
      n.removeLeftChild();
    } else {
      removeLeaves(n.left);
    }
  }
  // repeat for right child
  // ...
}

isLeaf, removeLeftChild and removeRightChild should be trivial to implement.

polygenelubricants
+1 for `isLeaf`
Heinzi