概述:二叉排序树也叫二叉查找树,二叉搜索树:BST,对于二叉树中的任何一个非叶子节点,要求左节点比当前节点值小,右子节点比当前节点值大。
生成二叉查找树的流程
//代理类
public class BinaryTree {
Node root;
public void setRoot(Node root){
this.root = root;
}
public Node getRoot(){
return root;
}
public BinaryTree(Node node) {
setRoot(node);
}
public void add(Node node) {
if(root !=null) {
root.add(node);
}
}
public void middleShow() {
if(root != null) {
root.midShow();
}
}
}
//生成二叉排序树的类
public class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node [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 midShow() {
if(this.left != null) {
this.left.midShow();
}
System.out.print(this.toString());
if(this.right != null) {
this.right.midShow();
}
}
}
//测试类
public class Test {
public static void main(String[] args) {
int[] arr = new int[] {4,2,6,8,1,56,32,58};
//创建一个Node类型的动态数组
List<Node>nodes = new ArrayList<Node>();
//把Node类型加到List中
for(int a:arr) {
nodes.add(new Node(a));
}
//初始化
BinaryTree bt = new BinaryTree(nodes.get(0));
//循环赋值
for(int i =1;i<nodes.size();i++) {
bt.add(nodes.get(i));
}
//中序遍历
bt.middleShow();
}
}