文章目录
- 【1】代码:
- ①Node节点
- ②BST binarySortTree二叉排序树:
- ③ 测试代码:
- 【2】测试结果:
【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
②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】测试结果:
- 待测试数据:
- 结果: