Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

BINARY TREE & RECURSIVE INSERT METHOD

807600Dec 3 2007 — edited Dec 6 2007
PLEASE HELP ME!
I hav a final assignment for my second year at uni and i can't get it to work!
The assignment involves this code:
public class BST 
{
	private BSTNode root;
	public BST () 
           {
	            // Construct an empty BST.
		root = null;
	}
	
	public class BSTNode 
            {
	           // BSTNode constructor, sets up Node containing elem and two null links
		protected Comparable element;
		protected BSTNode left, right;
		protected BSTNode (Comparable elem) 
                        {
			element = elem;
			left = null;  right = null;
		}
	} 
	
	public BSTNode getRoot() 
           {
	            // return the root of the tree
		return root;
	}
	
	public void insert (Comparable elem) 
           {
	            // insert an elem into the tree
		int direction = 0;
		BSTNode parent = null, curr = root;
		for (;;) 
                       {
			if (curr == null) 
                                   {
				BSTNode ins = new BSTNode(elem);
				if (root == null)  root = ins;
				else if (direction < 0)
					parent.left = ins;
				else  parent.right = ins;
				return;
			} 
			direction = elem.compareTo(curr.element);
			if (direction == 0)  return;
			parent = curr;
			if (direction < 0)  curr = curr.left;
			else  curr = curr.right;
		}
	} 

	public void printInOrder (BSTNode root) 
           {
		// Print, in ascending order, all the elements in the BST subtree 
		// whose topmost node is root.
		if (root != null) 
                       {
			printInOrder(root.left);
			System.out.println(root.element);
			printInOrder(root.right);
		}
	} 
}
THE QUESTION IS: Turn the insert method in class BST into a recursive one. You should pass the root to the method as follows.

public void insertR (BSTNode root, Comparable elem)

You would insert at the root if the tree is empty, otherwise you would insert in the left subtree if the element is smaller than the root element and in the right subtree if the element is larger than the root element.


HAND IN DATE IS THURSDAY 6th December, please help! thank you for your time :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 3 2008
Added on Dec 3 2007
22 comments
2,406 views