class JD
{
int data;//数据
JD left; //左儿子
JD right;//右儿子 public JD(int data)
{
this.data = data;
} public String toString()
{
return data+"";
}
}class Tree
{
JD root;//根接点
JD parrent;//父亲
boolean b;public boolean add(int d){
JD jd = new JD(d);
if(root == null) //如果根节点为空,那么把新节点加给根节点
root = jd;
else{
JD current = root;
while(current != null) { //是找到一个位置加新节点
if(d == current.data)//如果已经存在,则直接返回false 表示加失败
return false;
else if(d > current.data){//如果该值大于当前节点,那么应该往右边找
parrent = current; //记录要加新节点的父节点
b = true; //记录是左边还是右边,
current = current.right;
}else if(d < current.data)
{
parrent = current;
b = false;
current = current.left;
}
}
if(b)// 如果是右儿子为空 ,就加父节点的右边
parrent.right = jd;
else
parrent.left = jd;
}
return true;
}}
public class TestTree
{
public static void main(String[] args)
{
Tree t = new Tree();
t.add(5);
t.add(7);
t.add(3);
t.add(9);
t.add(1);
t.add(8);
t.add(13);
t.add(4);
t.p();
}
}
{
int data;//数据
JD left; //左儿子
JD right;//右儿子 public JD(int data)
{
this.data = data;
} public String toString()
{
return data+"";
}
}class Tree
{
JD root;//根接点
JD parrent;//父亲
boolean b;public boolean add(int d){
JD jd = new JD(d);
if(root == null) //如果根节点为空,那么把新节点加给根节点
root = jd;
else{
JD current = root;
while(current != null) { //是找到一个位置加新节点
if(d == current.data)//如果已经存在,则直接返回false 表示加失败
return false;
else if(d > current.data){//如果该值大于当前节点,那么应该往右边找
parrent = current; //记录要加新节点的父节点
b = true; //记录是左边还是右边,
current = current.right;
}else if(d < current.data)
{
parrent = current;
b = false;
current = current.left;
}
}
if(b)// 如果是右儿子为空 ,就加父节点的右边
parrent.right = jd;
else
parrent.left = jd;
}
return true;
}}
public class TestTree
{
public static void main(String[] args)
{
Tree t = new Tree();
t.add(5);
t.add(7);
t.add(3);
t.add(9);
t.add(1);
t.add(8);
t.add(13);
t.add(4);
t.p();
}
}
再有就是采用线索树或是采用Morris算法,楼主可以上网或查资料搜搜
具体程序不给你,呵呵