package Tree;
/**
* 1.查询是否存在结点,如果不存在,插入
*/
public class BiTee {
protected BiTNode head;
private BiTNode p;//父节点
public BiTee(int data){
head=new BiTNode(data);
}
public boolean SeachNode(BiTNode T,int key,BiTNode pre){
if (T==null){
p=pre;
return false;
}else{
if (T.data==key){
return true;
}else {
if (T.data>key){
//放左子树
SeachNode(T.lchirld,key,T);
}else {
//放右子树
SeachNode(T.rchild,key,T);
}
}
}
return false;
}
//添加元素
public void createNode(int data){
if (!SeachNode(head,data,head)){
if (p.data>data){
BiTNode s=new BiTNode(data);
p.lchirld=s;
}else {
BiTNode s=new BiTNode(data);
p.rchild=s;
}
}
}
public void print(BiTNode pre){
if (pre==null){
return;
}
System.out.println(pre.data);
print(pre.lchirld);
print(pre.rchild);
}
public static void main(String[] args) {
int bj[]=new int[]{30,50,68,23,89,10,6,5,8};
BiTee biTee=new BiTee(bj[0]);
for (int i=1;i<bj.length;i++){
biTee.createNode(bj[i]);
}
biTee.print(biTee.head);
}
}
class BiTNode{
protected int data;
protected BiTNode lchirld,rchild;
public BiTNode(){}
public BiTNode(int data){
this.data=data;
}
}