思路分析
package com.shujujiegou;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ran {
public static void main(String[] args) {
int []arr={7,3,10,12,5,1,9};
erchapaixushu erchapaixushu = new erchapaixushu();
for (int i=0;i<arr.length;i++){
erchapaixushu.add(new HeroNode(arr[i]));
}
erchapaixushu.zhongxu();
}
}
//创建二叉排序树
class erchapaixushu{
private HeroNode root;
//添加节点的方法
public void add(HeroNode heroNode){
if(root==null){
root=heroNode;
}else {
root.add(heroNode);
}
}
//中序遍历
public void zhongxu(){
if (root!=null){
root.zhongxu();
}else {
System.out.println("空");
}
}
}
class HeroNode{
int value;
HeroNode zuo;
HeroNode you;
public HeroNode(int value) {
this.value = value;
}
@Override
public String toString() {
return "HeroNode{" +
"value=" + value +
'}';
}
//添加节点
public void add(HeroNode node){
//递归的形式添加节点,注意需要满足二叉排序树的要求
if(node==null){
return;
}
//传入的节点的值,和我们的当前的根节点的值的关系
if(node.value<this.value){
if(this.zuo==null){
this.zuo=node;
}else {
this.zuo.add(node);
}
}
if(node.value>=this.value){
if(this.you==null){
this.you=node;
}else {
this.you.add(node);
}
}
}
public void zhongxu(){
if(this.zuo!=null){
this.zuo.zhongxu();;
}
System.out.println(this);
if(this.you!=null){
this.you.zhongxu();
}
}
}
代码实现效果如下: