二叉搜索树(模板)

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);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值