Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My remove method for the BST is not working correctly. I keep getting null pointer exceptions and I don't think I am actually removing anything.

Here is my the class that that main method uses:
import java.io.*;
import java.util.*;

///////////////////////////////////////////////////////////////////////////////
class BSTNode<T>
{	T key;
	BSTNode<T> left,right;
	BSTNode( T key, BSTNode<T> left, BSTNode<T> right )
	{	this.key = key;
		this.left = left;
		this.right = right;
	}
}

///////////////////////////////////////////////////////////////////////////////////////
class Queue<T>
{	LinkedList<BSTNode<T>> queue;
	Queue() { queue =  new LinkedList<BSTNode<T>>(); }
	boolean empty() { return queue.size() == 0; }
	void enqueue( BSTNode<T>  node ) { queue.addLast( node ); }
	BSTNode<T>  dequeue() { return queue.removeFirst(); }
	// THROWS NO SUCH ELEMENT EXCEPTION IF Q EMPTY
}

////////////////////////////////////////////////////////////////////////////////
class BSTreeP6<T>
{
	private BSTNode<T> root;
	private boolean addAttemptWasDupe=false;
	@SuppressWarnings("unchecked")
	public BSTreeP6( String infileName ) throws Exception
	{
		root=null;
		Scanner infile = new Scanner( new File( infileName ) );
		while ( infile.hasNext() )
			add( (T) infile.next() ); // THIS CAST RPODUCES THE WARNING
		infile.close();
	}

	public int size()
	{
		return countNodes(); 
	}

	// DUPES BOUNCE OFF & RETURN FALSE ELSE INCR COUNT & RETURN TRUE
	@SuppressWarnings("unchecked")
	public boolean add( T key )
	{	addAttemptWasDupe=false;
		root = addHelper( this.root, key );
		return !addAttemptWasDupe;
	}
	@SuppressWarnings("unchecked")
	private BSTNode<T> addHelper( BSTNode<T> root, T key )
	{
		if (root == null) return new BSTNode<T>(key,null,null);
		int comp = ((Comparable)key).compareTo( root.key );
		if ( comp == 0 )
			{ addAttemptWasDupe=true; return root; }
		else if (comp < 0)
			root.left = addHelper( root.left, key );
		else
			root.right = addHelper( root.right, key );

		return root;
    } // END addHelper


	// ITS A SEARCH - ONE OF FEW OPS YOU CAN DO ITERATIVELY
	public boolean contains( T key )
	{
		return contains( this.root, key  );
	}
	@SuppressWarnings("unchecked")
	private boolean contains( BSTNode<T> root, T key  )
	{
		if (root == null) return false;
		int comp = ((Comparable)key).compareTo( root.key );
		if ( comp == 0 ) return true;
		if (comp < 0) return contains(root.left, key );
		return contains(root.right, key );
	}

	public int countNodes()
	{
		return countNodes( root );
	}
	private int countNodes( BSTNode root)
	{
		if (root==null) return 0;
		return 1 + countNodes(root.left) + countNodes(root.right);
	}
		
	public int countLevels()
	  {
		return countLevels( root ); 
	  }
	  private int countLevels( BSTNode root)
	  {
		if (root==null) return 0;
		return 1 + Math.max( countLevels(root.left), countLevels(root.right) );
	  }
	  
	  public int[] calcLevelCounts()
	  {
		int levelCounts[] = new int[countLevels()];
		calcLevelCounts( root, levelCounts, 0 );
		return levelCounts;
	  }
	  private void calcLevelCounts( BSTNode root, int levelCounts[], int level )
	  {
		if (root==null)return;
		++levelCounts[level];
		calcLevelCounts( root.left, levelCounts, level+1 );
		calcLevelCounts( root.right, levelCounts, level+1 );
	  }

	// INORDER TRAVERSAL REQUIRES RECURSION
	public void printInOrder()
	{
		printInOrder( this.root );
		System.out.println();
	}
	private void printInOrder( BSTNode<T> root )
	{
		if (root == null) return;
		printInOrder( root.left );
		System.out.print( root.key + " " );
		printInOrder( root.right );
	}

	public void printLevelOrder()
	{	if (this.root == null) return;
		Queue<T> q = new Queue<T>();
		q.enqueue( this.root ); // this. just for emphasis/clarity
		while ( !q.empty() )
		{	BSTNode<T> n = q.dequeue();
			System.out.print( n.key + " " );
			if ( n.left  != null ) q.enqueue( n.left );
			if ( n.right != null ) q.enqueue( n.right );
		}
	}

	// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
	// DO NOT MODIFY ANYTHING ABOVE THIS LINE.  YOU FILL IN ALL THE CODE BELOW
	// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

	// return true only if it finds/removes the node
	public boolean remove( T key2remove )
	{
		
		return remove(this.root, key2remove);			  
	}
	private BSTNode<T> miniElement(BSTNode<T> root)
	{
		if(root.left == null)
			return root;
		else
			return miniElement(root.left);
	}
	private BSTNode<T> removeMin(BSTNode<T> root) 
	{
		if (root.left != null) 
		{
			return removeMin(root.left);
		} 
		if(root.right == null)
		{
			root.left = null;
		} 
		else 
		{ 
			root.left = removeMin(root.right);
		}
		return root;
	}
	@SuppressWarnings("unchecked")
	private boolean remove (BSTNode<T> root, T key2remove)
	{
		if(root == null)
			return false;

		T rootData = root.key;
		int comp = ((Comparable)key2remove).compareTo(rootData);
		if (comp == 0) 
		{
				if (root.left == null && root.right == null) 
				{
					root = null;
					return true;
				} 
				else if (root.left != null && root.right != null) 
				{
					BSTNode<T> temp = root;
					BSTNode<T> thing = miniElement(root.left);
					root.key = thing.key;
					removeMin(root.right);
					return true;
				}
				else if(root.left == null && root.right != null)
				{
					root= root.right;
					return true;
				}
				else if(root.left != null && root.right == null)
				{
					root = root.left;
					return true;
				}
				
		}
		if (comp < 0) 
		{
			if (root.left.key.equals(key2remove)) 
			{
				if (root.left.left == null || root.left.right == null) 
				{
					root.left = null;
					return true;
				}
				else if (root.left.left != null && root.left.right != null) 
				{
					BSTNode<T> temp = root.left;
					BSTNode<T> thing = miniElement(root.left.left);
					root.key = thing.key;
					removeMin(root.left.right);
					return true;
				}
				else if(root.left.left == null && root.left.right != null)
				{
					root.left = root.left.right;
					return true;
				}
				else if(root.left.left != null && root.left.right == null)
				{
					root.left = root.left.left;
					return true;
				}
			}
			return remove(root.left, key2remove);
		}
		 if (comp > 0) 
		 {
				if (root.right.key.equals(key2remove)) 
				{
					if (root.right.right == null || root.right.left == null) 
					{
						root.right = null;
						return true;
					}
					else if (root.right.left != null && root.right.right != null) 
					{
						BSTNode<T> temp = root.right;
						BSTNode<T> thing = miniElement(root.right.left);
						root.key = thing.key;
						removeMin(root.right.right);
						return true;
					}
					else if(root.right.left == null && root.right.right != null)
					{
						root.right = root.right.right;
						return true;
					}
					else if(root.right.left != null && root.right.right == null)
					{
						root.right = root.right.left;
						return true;
					}
				}
				return remove(root.right, key2remove);
		 }
		 return false;
	}
		
}



Here is the main method:
public class BSTesterP6
{
	public static void main( String[] args ) throws Exception
	{
		BSTreeP6<String> tree1 = new BSTreeP6<String>( args[0] );
		System.out.format( "\ntree1: loaded from %s contains %d nodes on %d levels:\n", args[0], tree1.countNodes(), tree1.countLevels() );
		System.out.print("IN ORDER tree1:    "); tree1.printInOrder();
		System.out.print("LEVEL ORDER tree1: "); tree1.printLevelOrder();
		int[] levelCounts = tree1.calcLevelCounts();
		System.out.println();
		for (int i = 0 ; i<levelCounts.length; ++i )
			System.out.format("level:%2d   %d\n",i,levelCounts[i] );
		
		
		// REMOVE SEVERAL NODES WHO HAVE 2 CHILDREN
		tree1.remove( "C" ); tree1.remove( "I" ); tree1.remove( "P" ); 	tree1.remove( "W" ); // ALL HAVE 2 CHILDREN
		
		System.out.format( "\ntree1: after removing C, I, P, W, contains %d nodes on %d levels:\n", tree1.countNodes(), tree1.countLevels() );
		System.out.print("IN ORDER tree1:    "); tree1.printInOrder();
		System.out.print("LEVEL ORDER tree1: "); tree1.printLevelOrder();	
		levelCounts = tree1.calcLevelCounts();
		System.out.println();
		for (int i = 0 ; i<levelCounts.length; ++i )
			System.out.format("level:%2d   %d\n",i,levelCounts[i] );
		
		
		// REMOVE SEVERAL lEAVES
		tree1.remove( "J" ); tree1.remove( "S" ); tree1.remove( "Z" ); // ALL ARE LEAVES
		
		System.out.format( "\ntree1: after removing J, S, Z, contains %d nodes on %d levels:\n", tree1.countNodes(), tree1.countLevels() );
		System.out.print("IN ORDER tree1:    "); tree1.printInOrder();
		System.out.print("LEVEL ORDER tree1: "); tree1.printLevelOrder();
		levelCounts = tree1.calcLevelCounts();
		System.out.println();
		for (int i = 0 ; i<levelCounts.length; ++i )
			System.out.format("level:%2d   %d\n",i,levelCounts[i] );

		// REMOVE SEVERAL NODES WHICH HAVE EXACTLY ONE CHILD
		tree1.remove( "D" ); tree1.remove( "K" ); tree1.remove( "R" ); tree1.remove( "Y" ); // THESE HAVE EXACTLY 1 CHILD

		System.out.format( "\ntree1: after removing D, K, R, Y, contains %d nodes on %d levels:\n", tree1.countNodes(), tree1.countLevels() );
		System.out.print("IN ORDER tree1:    "); tree1.printInOrder();
		System.out.print("LEVEL ORDER tree1: "); tree1.printLevelOrder();
		levelCounts = tree1.calcLevelCounts();
		System.out.println();
		for (int i = 0 ; i<levelCounts.length; ++i )
			System.out.format("level:%2d   %d\n",i,levelCounts[i] );

		System.out.println();
		System.out.println( "Now attempting remove of A..Z");
		String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		for ( int i=0 ; i<alphabet.length() ; ++i )
		{
			if ( tree1.remove(alphabet.charAt(i)+"") )
			{
				System.out.format("\nremove(%c) successful: ", alphabet.charAt(i) ); 
				tree1.printLevelOrder();
			}
			else
			{
				System.out.format("\nremove(%c) failure:    ", alphabet.charAt(i) );
				tree1.printLevelOrder();
			}
		}
	}
}


Here is the output file
            M
     F             T
  C     I      P      W
A  D  G   K  N   R  U   Y
 B  E  H J L  O Q S  V X Z


What I have tried:

I need help figuring it out. 
Posted
Updated 28-Oct-19 18:35pm

1 solution

It is time to learn Debugger.
Quote:
My remove method for the BST is not working correctly. I keep getting null pointer exceptions and I don't think I am actually removing anything.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.

Binary search tree - Wikipedia[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900