/**
* 构建二叉查找树,并查找
* @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;
}
}
}