1

I am working on a lab that requires me to create a remove method for a binary search tree. Here is my code for my remove method.

public void remove(T r)
  {
    remove(root, r);
  }

  private TreeNode <T> remove(TreeNode <T> tree, T r)
  {
    if(tree == null)
    return tree;
    if(r.compareTo(tree.getValue())<0)  // my num is smaller
        tree.setLeft(remove(tree.getLeft(), r));
    else if (r.compareTo(tree.getValue())>0)  // my num is larger
        tree.setRight(remove(tree.getRight(), r));
    else  // this is my number
    {
      if(tree.getLeft() == null && tree.getRight() == null)
      return null;
      else if(tree.getLeft() == null)
      return tree.getRight();
      else if (tree.getRight() == null)
      return tree.getLeft();
    else
    {
      T min = getSmallest(tree.getRight());
      tree.setValue(min);
      //System.out.println("2 + " + toString(tree));
      tree.setRight(remove(tree.getRight(), min));
    }
  }
  return tree;
  }

The output I get when I run the code is:

Tree after removing 90. 70 80 85 98 100 120

Tree after removing 70. 80 85 98 100 120

Tree after removing 85. 80 98 100 120

Tree after removing 98. 80 100 120

Tree after removing 80. 100 120

Tree after removing 120. 100

Tree after removing 100. 100

I am not sure why it does not work only when there is only one node left in the binary tree. Any help is appreciated.

george1029
  • 21
  • 2

2 Answers2

0

You are probably calling tree.remove(r) in your code which does not return anything and does not change tree but only its childs or its value. A way to fix this is to change

public TreeNode<T> remove(T r)
  {
    return remove(root, r);
  }

and use

tree = tree.remove(r)

in your code. To see what is happening in your code: I suppose you have a constructor TreeNode(parent,left,right,value) so:

TreeNode<Integer> tree = new TreeNode(null,null,null,100);
tree.remove(100);
#remove(100) is called
#remove(root,100) is called
#remove(root,100) returns null after if(tree.getLeft() == null && tree.getRight() == null) without changing anything
#remove(100) returns
dcolazin
  • 831
  • 1
  • 10
  • 25
0

The root must also be updated, should the root node be deleted.

public void remove(T r) {
    root = remove(root, r);
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138