二叉排序树的创建和遍历
将一个二叉树中序遍历,就是将这个树的数据升序排列了
package com.wmq.binarysorttree;
/**
* 二叉排序树
*/
public class BinarySortTreeDemo {
public static void main(String[] args) {
int[] arr = {7,3,10,12,5,1,9};
BinarySortTree binarySortTree = new BinarySortTree();
//循环加入节点到二叉排序树
for (int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node(arr[i]));
}
//中序遍历
System.out.println("中序遍历结果");
binarySortTree.infixOrder();//1,3,5,7,9,10,12
}
}
//创建二叉树排序树
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("Error,null");
}
}
}
//创建节点
class Node{
int value;
Node left;
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 infixOrder(){
if (this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null){
this.right.infixOrder();
}
}
}