对于任何一个非叶子节点,要求左子树的值比当前节点的值小,右子树的值比当前节点的值大。如果有相同的值,则可以放置左右任意节点
package xmht.datastructuresandalgorithms.datastructure.binarysortTree;
/**
* @author shengjk1
* @date 2020/6/15
*/
public class BinarySortTree {
public static void main(String[] args) {
int[] arr = {7, 3, 10, 12, 5, -1, 9};
BinarySortTree1 binarySortTree = new BinarySortTree1();
for (int i : arr) {
binarySortTree.add(new Node(i));
}
System.out.println("中序遍历二叉树");
binarySortTree.infixOrder();
}
}
class BinarySortTree1 {
private Node root;
public void add(Node node) {
if (this.root != null) {
this.root.add(node);
} else {
root = node;
}
}
public void infixOrder() {
if (this.root != null) {
this.root.infixOrder();
}
}
@Override
public String toString() {
return "BinarySortTree1{" +
"root=" + root +
'}';
}
}
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 (node.value < this.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 infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.infixOrder();
}
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
}