数据结构--二叉查找树

/**
 * 构建二叉查找树,并查找
 * @author neu_fufengrui@163.com
 * 另外,二叉查找树可以转化成平衡二叉树,更有利于查找
 * 多路平衡二叉树,即所谓的B-树,文件系统中常见
 */
public class BinSearch {
	
	/**
	 * 初始化二叉查找树
	 *         45
	 *       24  53
	 *     12      90
	 */
	Node initTree(){
		Node root = new Node(45);
		Node lNode = new Node(24);
		Node llNode = new Node(12);
		Node rNode = new Node(53);
		Node rrNode = new Node(90);
		root.setLchild(lNode);
		lNode.setLchild(llNode);
		root.setRchild(rNode);
		rNode.setRchild(rrNode);
		return root;
	}
	/**
	 * 查找二叉查找树
	 */
	boolean searchTree(Node root, int key){
		if(root == null){
			return false;
		}
		if(root.getValue() == key){
			return true;
		}else if(root.getValue() > key){
			return searchTree(root.getLchild(), key);
		}else{
			return searchTree(root.getRchild(), key);
		}
	}
	
	public static void main(String[] args) {
		BinSearch handler = new BinSearch();
		Node root = handler.initTree();
		System.out.println(handler.searchTree(root, 13));
		
	}	
	
	/**
	 * 节点定义
	 * @author User
	 *
	 */
	class Node{
		private int value;
		private Node lchild;
		private Node rchild;
		public Node(int value){
			this(null, null, value);
		}
		public Node(Node lchild, Node rchild){
			this(lchild, rchild, -1);
		}
		public Node(Node lchild, Node rchild, int value){
			this.lchild = lchild;
			this.rchild = rchild;
			this.value = value;
		}
		public int getValue() {
			return value;
		}
		public void setValue(int value) {
			this.value = value;
		}
		public Node getLchild() {
			return lchild;
		}
		public void setLchild(Node lchild) {
			this.lchild = lchild;
		}
		public Node getRchild() {
			return rchild;
		}
		public void setRchild(Node rchild) {
			this.rchild = rchild;
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值