二叉排序树
定义:二叉排序树的查找过程是,通过采取二叉链表作为二叉排序树的存储结构。一个无序的数列,可以通过二叉树
中的排序树变成一个有序数列。
中序特点:所有节点都是左小右大
public class MyBtree {//创建一个实体类
private Node root;
class Node{
private int data; //给一个int变量接收
private Node left; //左边的值
private Node right; //右边的值
public void add(Node node) {
if(this.data > node.data){ //假设11为第一个值,如果第二个值小于11则走if
if(this.left == null ){ //如果11的左边没有值,则走if
this.left = node;//因为11的左边没有值,也就是说11算小的值,所有将11移到左边
}else {
this.left.add(node); //11左边有值
}
}
if(this.data < node.data){ //假设11为第一个值,如果第二个值大于11则走if
if(this.right == null ){ //如果11的右边没有值,则走if
this.right=node; //因为11的右边没有值,也就是说11算大的值,所有将11移到右边
}else {
this.right.add(node); //11右边有值
}
}
}
public void zhongxu() { //中序方法
if(this.left!=null){
this.left.zhongxu();
}
System.out.println(this.data);
if(this.right!=null){
this.right.zhongxu();
}
}
}
public void add(int data) {
Node node=new Node();
node.data=data;
if(root == null){
root=node;
}else {
root.add(node);
}
}
public void zhongxu() { //中序方法
root.zhongxu();
}
}
public class MyBtreeTest {
public static void main(String[] args) {
MyBtree tree=new MyBtree();
tree.add(11);
tree.add(7);
tree.add(18);
tree.add(5);
tree.add(8);
tree.add(2);
tree.add(3);
tree.add(24);
tree.zhongxu();
}
}
输出的结果是:2
3
5
7
8
11
18
24
比较绕的地方加了注释,希望能帮到读者,有不懂的地方可以留言问我,写的不好请见谅!