/**
* 構建二叉查找樹,並查找
* @author [email protected]
* 另外,二叉查找樹可以轉化成平衡二叉樹,更有利於查找
* 多路平衡二叉樹,即所謂的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;
}
}
}
數據結構--二叉查找樹
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.