【1】代码:
①Node节点
package algorithm.tree.binarySortTree_BST;
public class Node {
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
return val+"";
}
public void add(Node node){
if(node == null)
return;
if (node.val<this.val){
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);
}
}
}
}
②BST binarySortTree二叉排序树:
package algorithm.tree.binarySortTree_BST;
public class BTS {
Node root;
public void add(Node n){
if (root == null){
root = n;
}else{
root.add(n);
}
}
public void show(){
midOrder(root);
}
private void midOrder(Node n){
if (n == null)
return;
if (n.left != null){
midOrder(n.left);
}
System.out.println(n);
if (n.right != null){
midOrder(n.right);
}
}
}
③ 测试代码:
package algorithm.tree.binarySortTree_BST;
public class Test {
public static void main(String[] args) {
int[] arr = {4, 6, 2, 12, 45, 5, 123, 6, 2};
BTS tree = new BTS();
for (int t:arr) {
tree.add(new Node(t));
}
tree.show();
}
}
【2】测试结果:
- 待测试数据:

- 结果:
