package cn.mrlij.binarysorttree;
/**
* 二叉排序树
*/
public class BinarySortTreeDemo {
public static void main(String[] args) {
BinarySortTree bst = new BinarySortTree();
int[] arr = {2,67,3,5,99,34};
for(int i = 0; i < arr.length;i++){
bst.add(new Node(arr[i]));
}
bst.infixOrder();
}
}
class BinarySortTree{
private Node root;
public void add(Node node){
if(root == null){
root = node;
}else {
root.add(node);
}
}
public void infixOrder(){
if(root!=null){
root.infixOrder();
}else{
System.out.println("二叉排序树为空,不能遍历!");
}
}
}
class Node{
int val;
Node left;
Node right;
@Override
public String toString() {
return "Node{" +
"val=" + val +
'}';
}
public Node(int val) {
this.val = val;
}
//添加节点,构成二叉排序树
public void add(Node node){
if(node == null){
return;
}
//判断当前节点的值是否小于传入的节点值
if(this.val>node.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);
}
}
}
//中序遍历
public void infixOrder(){
if(this.left !=null){
this.left.infixOrder();
}
System.out.println(this);
if(this.right !=null){
this.right.infixOrder();
}
}
}