package Test1;
public class L7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Node q = new Node();
q.insert(2);
q.insert(5);
q.insert(1);
System.out.println(q.val);
System.out.println(q.lch.val);
System.out.println(q.rch.val);
System.out.println(q.find(5));
System.out.println(q.find(2));
System.out.println(q.find(1));
System.out.println(q.find(11));
q.remove(q, 2);
System.out.println("=====");
q.show(q);
}
}
//二叉搜索树
class Node {
int val;
boolean f = false;
Node lch, rch;
public void insert(int x) {
if (!f) {
val = x;
f = true;
} else {
if (x < val) {
lch = new Node();
lch.insert(x);
} else {
rch = new Node();
rch.insert(x);
}
}
}
public boolean find(int x) {
if (x == val)
return true;
else if (x < val) {
if (this.lch == null)
return false;
else
return lch.find(x);
} else if (x > val) {
if (this.rch == null)
return false;
else
return rch.find(x);
}
return false;
}
public Node remove(Node p,int x) {
if(p==null)return null;
else if(x<val) p.lch=lch.remove(lch, x);
else if(x>val) p.rch=rch.remove(rch, x);
else if(p.lch==null) {
Node q=p.rch;
return q;
}else if(p.lch.rch==null) {
Node q=p.lch;
q.rch=p.rch;
return q;
}else {
Node q;
for(q=p.lch;q.lch.lch!=null;q=q.lch);
Node r=q.lch;
q.rch=r.rch;
r.lch=p.lch;
r.rch=p.rch;
return r;
}
return p;
}
public void show(Node q) {
System.out.print(q.val+" ");
if(q.lch!=null)
show(q.lch);
if(q.rch!=null)
show(q.rch);
}
}