代码:
package Tree;
public class BSTree {
public Node root; //记录根节点
public Node current;
//构建树节点
class Node{
public Node left;
public Node right;
public int data;
public Node(int data){
this.left=null;
this.right=null;
this.data=data;
}
}
//增加节点
public void addNode(int data){
if(root==null){
root=new Node(data); //为空树
}
else {
current=root;
while (current!=null){ //向下寻找叶子节点
if (data<=current.data){
if (current.left==null){
current.left=new Node(data);
break;
}
current=current.left; //指针移动
}else {
if(current.right==null){
current.right=new Node(data);
break;
}
current=current.right;
}
}
}
}
//中序遍历
public void inOrderPrintTree(Node node){
if (node!=null){
inOrderPrintTree(node.left);
System.out.print(node.data+",");
inOrderPrintTree(node.right);
}
}
//查找值为val的节点
public Node searchNode(int data){
if (root==null){
return null;
}
current=root;
//当current不为空,并且没找到
while (current!=null && data!=current.data){
if(data>current.data){
current=current.right;
}else if(data<current.data){
current=current.left;
}else { //相等时
return current;
}
}
return current;
}
//查找树中的最小值
public Node searchMin(Node root){
if(root==null)
return null;
while(root.left!=null)
root=root.left;
return root;
}
//查找树种的最大值
public Node searchMax(Node root){
if(root==null){
return null;
}
while (root.right!=null)
root=root.right;
return root;
}
/* 未完成 : //寻找前驱节点(查找数据值小于该节点的最大节点)
public Node preNode(Node node){
if (node==null){
return null;
}
//如果node存在左孩子,则node的前驱节点就是 以其左孩子为根的自数的最大节点
if (node.left!=null){
return searchMax(node.left);
}
*//*
* 如果它没有左孩子,则有以下两种可能
* 1、node是一个右孩子,则 node 的前驱节点 为 它的父节点
* 2、node是一个左孩子,则 前驱节点为node的某一个祖先节点的父节点,而且该祖先节点是作为其父节点的右儿子*//*
Node p=node.
}*/
public static void main(String[] args) {
BSTree myTree=new BSTree();
myTree.addNode(5);
myTree.addNode(15);
myTree.addNode(3);
myTree.addNode(7);
myTree.addNode(11);
myTree.addNode(17);
myTree.addNode(6);
myTree.addNode(4);
myTree.addNode(1);
myTree.inOrderPrintTree(myTree.root);//中序遍历树
System.out.println();
Node node = myTree.searchNode(11); //查找树中值为data的节点
System.out.println(node==null?null:node.data);
Node min = myTree.searchMin(myTree.root);//查找树中的最小值
System.out.println(min==null?null:min.data);
Node max = myTree.searchMax(myTree.root);
System.out.println(max==null?null:max.data);
}
}
BST查找的时间复杂度:
因为n个节点,最大的高度为n-1,则最多查找n次。
最小的高度为logN向下取整,所以最多查找logN+1。