代码展示
节点类
package demo10;
public class Node {
int value;
Node left;
Node right;
public Node(int value){
this.value=value;
}
/**
* 向子树中添加节点
* @param node
*/
public void add(Node node) {
if(node==null){
return;
}else{
//判断传入的节点的值比当前子树的根节点的值大还是小
//添加的节点比当前节点的值更小
if(node.value<this.value){
//如果左节点为空
if(this.left==null){
this.left=node;
}
//如果不为空
else{
this.left.add(node);
}
//添加的节点比当前节点的值大
}else{
if(this.right==null){
this.right=node;
}else{
this.right.add(node);
}
}
}
}
/**
* 中序遍历二叉排序树,从小到大排序
* @param node
*/
public void midShow(Node node) {
if(node==null){
return;
}
midShow(node.left);
System.out.print(node.value+" ");
midShow(node.right);
}
/**
* 查找节点
* @param value
* @return
*/
public Node search(int value) {
if(this.value==value){
return this;
}else if(value<this.value){
if(left==null){
return null;
}
return left.search(value);
}else{
if(right==null){
return null;
}
return right.search(value);
}
}
}
树实体类
package demo10;
public class BinarySortTree {
Node root;
/**
* 向二叉排序树中添加节点
* @param node
*/
public void add(Node node){
//如果是一棵空树
if(root==null){
root=node;
}else{
root.add(node);
}
}
/**
* 中序遍历二叉排序树,从小到大的顺序
*/
public void midShow(){
if(root!=null){
root.midShow(root);
}
}
/**
* 节点的查找
* @param value
* @return
*/
public Node search(int value){
if(root==null){
return null;
}else{
return root.search(value);
}
}
}
测试类
package demo10;
public class TestBinarySortTree {
public static void main(String[] args) {
int[] arr = new int[]{7,3,10,12,5,1,9};
//创建一棵二叉排序树
BinarySortTree bst = new BinarySortTree();
//循环添加
for(int i:arr){
bst.add(new Node(i));
}
//查看树中的值
System.out.println("二叉排序树中序遍历:");
bst.midShow();
System.out.println();
System.out.println("=============");
Node node = bst.search(10);
System.out.println(node.value);
Node node2 = bst.search(20);
System.out.println(node2);
}
}