//测试
public static void main(String[] args) {
int[] arr = {7, 3, 10, 12, 5, 1, 9};
BST bst = new BST();
//循环添加节点
for (int i = 0; i < arr.length; i++) {
bst.add(new Node(arr[i]));
}
//中序遍历查看
System.out.println("中序遍历");
bst.infixOrder();
}
//二叉排序树
class BST{
private Node root;
//中序遍历
public void infixOrder(){
if (root != null){
root.infixOrder();
}else {
System.out.println("树是空的");
}
}
//添加节点
public void add(Node node){
if (root == null){
root = node;
}else {
root.add(node);
}
}
}
//节点
class Node {
int value;
Node left;
Node right;
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(){
if (this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null){
this.right.infixOrder();
}
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
‘}‘;
}
}
原文:https://www.cnblogs.com/mx-info/p/14869151.html