二叉排序树 ( Binary Sort Tree) 或者为空;或者是具有如下特性的二叉树:
(1)若根的左子树不空,则左子树上所有结点的关键字均小于根结点的关键字;
(2)若根的右子树不空,则右子树上所有结点的关键字均大于根结点的关键字;
(3)根的左、右子树也分别是二叉排序树。
package com.wuzhixin.tree;
import javax.xml.crypto.NodeSetData;
import java.util.ArrayList;
import java.util.List;
public class BinarySortTree {
public static void main(String[] args) {
int []arr = {7,3,10,12,5,1,9};
List<Node2> nodes = new ArrayList<>();
Node2 node = null;
SortTree sortTree = new SortTree();
for(int i=0;i<arr.length;i++){
node = new Node2(arr[i]);
sortTree.add(node);
}
sortTree.getRoot().midShow();
}
}
//排序树
class SortTree{
private Node2 root;
public Node2 getRoot() {
return root;
}
public void setRoot(Node2 root) {
this.root = root;
}
public void add (Node2 node){
if(root==null){
root=node;
}
else{
root.add(node);
}
}
public void midOrder(){
if(root==null){
return;
}else{
root.midShow();
}
}
}
class Node2 {
private Node2 left;
private Node2 right;
private Integer value ;
public Node2(Integer value) {
this.value = value;
}
@Override
public String toString() {
return "Node2{" +
"value=" + value +
'}';
}
public Node2 getLeft() {
return left;
}
public void setLeft(Node2 left) {
this.left = left;
}
public Node2 getRight() {
return right;
}
public void setRight(Node2 right) {
this.right = right;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
/**
* 添加节点的方法,
* 递归的形式添加节点,满足二叉排序树
* @param node
*/
public void add(Node2 node){
if(node == null){
return;
}
//如果当前加入的节点小于当树的根节点,则向左边添加
if(node.getValue()<=this.getValue()){
if(this.getLeft()==null){
this.setLeft(node);
}//否则向左递归添加
else{
this.getLeft().add(node);
}
}else{
if(this.getRight()==null){
this.setRight(node);
}else{
this.getRight().add(node);
}
}
}
//中序遍历
public void midShow(){
if(this.getLeft()!=null){
this.getLeft().midShow();
}
System.out.println(this);
if(this.getRight()!=null){
this.getRight().midShow();
}
}
}
运行如下: