package
public class BinarySortTreeDemo {
public static void main(String[] args) {
int[] arr = {7,3,10,12,5,1,9,8,7};
BinarySortTree binarySortTree = new BinarySortTree();
//循环添加节点到二叉排序树
for (int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node(arr[i]));
}
//中序遍历二叉排序树
System.out.println("中序遍历二叉排序树");
binarySortTree.infixOrder();
}
}
//创建二叉排序树
class BinarySortTree{
private Node root;
public void add (Node node){
if (root == null) {
root = node;
}else {
root.add(node);
}
}
//遍历二叉树,其实是由Node类里的infixOrder完成的。
public void infixOrder(){
if (root != null) {
root.infixOrder();
}else {
System.out.println("二叉树为空,不能遍历");
}
}
}
class Node {
int value;
Node left;
Node right;
@Override
public String toString() {
return "Node [" +
"value=" + value +
']';
}
public Node(int value) {
this.value = value;
}
public void add(Node node){
if(node == null){
return;
}
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);
}
}
}
//先序遍历, 中序遍历,后序遍历。 ,先,中,后指的是伪根节点所在(根,左节点,右节点),中的位置
//不同的遍历方式,就是调整下面的三个位置
public void infixOrder(){
System.out.println(this +" 0"); //打印为伪根节点
if (this.left != null) { //打印左节点
this.left.infixOrder();
}
if (this.right != null) { //打印右节点
this.right.infixOrder();
}
//System.out.println(this+"1");
}
}
下面是根据数组里的数据,在内存中存储的结构图,和按先序遍历的顺序,以及代码运行出来的结果。
程序运行出来的结果: