Computing.Net > Forums > Programming > binary search tree with java ?

Computing.Net: Over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to sign up now, it's free!

binary search tree with java ?

Reply to Message Icon

Original Message
Name: Hn
Date: July 15, 2002 at 17:42:06 Pacific
Subject: binary search tree with java ?
Comment:

i have a binary search tree data structure with C.

typedef root *bst;
struct {
int item;
bst left;
bst right;
} bst;

but how to declare a binary search tree in java, since java doesn't have pointer.

i am a beginner in java. any answer would be approciate.


Report Offensive Message For Removal


Response Number 1
Name: t1
Date: July 16, 2002 at 05:31:01 Pacific
Reply: (edit)

Its still very easy to do in java. You will need to write two methods.. a compair function and the binary tree.

====Compair=====

public class pInteger implements pComparable{
int i;

public pInteger(){
}
public pInteger(int j){
set(j);
}
public int get(){
return i;
}
public void set(int j){
i = j;
}
public String toString(){
return ""+get();
}
public int compareTo(Object o){
if(o instanceof pInteger)
if(get() > ((pInteger)o).get())
return 1;
else if(get() < ((pInteger)o).get())
return -1;
return 0;
}
}

=====Binary Tree===============

import pComparable;

public class pBinarySearchTree{

public pBinarySearchTree(){
super();
}

public pBinarySearchTree(Object o){
super(o);
}

public void print(){
print(2);
}

public void insert(pComparable o){
pTwoChildNode t,q;
for(q = null, t = getRoot();
t != null && o.compareTo(t.getData()) != 0;
q = t,t = o.compareTo(t.getData()) < 0
? t.getLeft():t.getRight());
if(t != null)
return;
else if(q == null)
setRoot(new pTwoChildNode(o));
else if(o.compareTo(q.getData()) < 0)
insertLeft(q,o);
else
insertRight(q,o);
}
}


THis should give you a good start.


Report Offensive Follow Up For Removal







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home








Do you own an iPhone?

Yes
No, but soon
No


View Results

Poll Finishes In 7 Days.
Discuss in The Lounge
Poll History




Data Recovery Software