Skip to Main Content

Java Programming

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 Search Tree

807605Aug 1 2007 — edited Aug 6 2007
I'm trying to make a binary search tree involving two classes:
public class BinaryNode
{
	private Object value;
	private BinaryNode left;
	private BinaryNode right;

	public BinaryNode (Object value, BinaryNode left, BinaryNode right)
	{
		this.value = value;
		this.left = left;
		this.right = right;
	}
	public void setValue(Object value)
	{
		this.value = value;
	}
	public BinaryNode getLeft()
	{
		return left;
	}
	public void setLeft(BinaryNode left)
	{
		this.left = left;
	}
	public BinaryNode getRight() 
	{
		return right;
	}
	public void setRight(BinaryNode right)
	{
		this.right = right;
	}
	public Object getValue()
	{
		return value;
	}
}
public class BinaryTree
{
	private BinaryNode root;
	
	public BinaryTree(BinaryNode root)
	{
		this.root = root;
	}

	public void insert(BinaryNode node)
	{
		if(root.getLeft() == null)
		{
			root.setLeft(node);
		}
		else if(root.getRight() == null)
		{
			root.setRight(node);
		}
		else
		{
			BinaryNode n = root.getLeft();
			while(n!=null)
			{
				n = n.getLeft();
			}
			n.setLeft(node);
		}
	}
	public void inorder(BinaryNode node)
	{
		if(node==null)
		{
			return;
		}
		inorder(node.getLeft());
		System.out.println(node.getValue());//visit the node
		inorder(node.getRight());
	}
}
I need to write a BinarySearchTree that extends from BinaryTree. I have to override the insert method from BinaryTree so that it behaves like a BinarySearchTree. I also need to implement a remove method as well.

I understand how it is inserted, I just have trouble translating what I understand visually into codes.
public void insert(BinaryNode node)
	{
		//if null condition here
//else if the value being inserted is > the root of the subtree then value is inserted to right
//else insert to left	
	}
After that, I need to make a remove method, which I understand is the difficult part.

I've searched through the internet, found some helpful tips and such, but they don't work for my set up.

Any tips here would be helpful.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 3 2007
Added on Aug 1 2007
6 comments
283 views