二叉排序树
二叉查找树、二叉搜索树 BST;对于二叉树中的任何非叶子节点 要求左子节点比当前节点值小,右子节点比当前节点值大。
实现
/**
* @Description 二叉排序树的节点
* @auther Eleven
* @create 2020-04-09 20:43
**/
public 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 (this.value>node.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 midPrint(Node root) {
if (root == null){
return;
}
midPrint(root.left);
System.out.println(root.value);
midPrint(root.right);
}
}
/**
* @Description 二叉排序树
* @auther Eleven
* @create 2020-04-09 20:43
**/
public class BinarySortTree {
Node root;
public void add(Node node){
if (root == null ){
root=node;
}else{
root.add(node);
}
}
public void midPrint() {
if (root !=null){
root.midPrint(root);
}
}
}
//测试方法
public static void main(String[] args) {
BinarySortTree binarySortTree = new BinarySortTree();
int[] arr = new int[]{7,2,10,12,5,1,9};
for (int i:arr){
binarySortTree.add(new Node(i));
}
binarySortTree.midPrint();
}