/**
* @author:xingquanxiang createTime:2019/12/14 19:58
* description: 二叉搜索树、二叉排序树
* 特点:
* 1.如果左子树不为空,则左子树上结点的值都小于根节点
* 2.如果右子树不为空,则右子树上结点的值都大于根节点
*/
public class BinarySearchTree {
int data;
BinarySearchTree left;
BinarySearchTree right;
public BinarySearchTree(int data) {
this.data = data;
this.left = null;
this.right = null;
}
public void insert(BinarySearchTree root, int data) {
if (root != null) {
if (root.data < data){
if (root.right != null){
insert(root.right, data);
}else{
root.right = new BinarySearchTree(data);
}
}else{
if (root.left !=null){
insert(root.left, data);
}else{
root.left = new BinarySearchTree(data);
}
}
} else {
root = new BinarySearchTree(data);
}
}
/**
* 中序遍历 左 根输出 右
* @param root
*/
public void inOrderPrint(BinarySearchTree root){
if (root !=null){
inOrderPrint(root.left);
System.out.println(root.data);
inOrderPrint(root.right);
}
}
public static void main(String[] args) {
int[] data = {5,9,0,1,2,3,10};
BinarySearchTree root = new BinarySearchTree(data[0]);
for (int i = 1; i < data.length; i++) {
root.insert(root, data[i]);
}
root.inOrderPrint(root);
}
}
来源:CSDN
作者:weixin_41808843
链接:https://blog.csdn.net/weixin_41808843/article/details/103542665