package demo1;
public class BinarySortTree {
public static void main(String[] args) {
//测试
int[] arr = {7,3,10,12,5,1,9};
CreatTree creatTree = new CreatTree();
for (int i = 0; i < arr.length; i++) {
creatTree.addTree(new Node(arr[i]));
}
creatTree.showTree();
}
}
//创建二叉排序树
class CreatTree{
private Node root;
//添加树
public void addTree(Node node){
if (root == null){
root = node;
}else {
root.add(node);
}
}
//遍历树
public void showTree(){
root.midList();
}
}
//创建节点
class Node{
private int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
public Node() {
}
public int getValue() {
return value;
}
public void setValue(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 (node.value >= this.value){
if (this.right == null){
this.right = node;
}else {
this.right.add(node);
}
}
}
//中序遍历节点
public void midList(){
if (this.left != null){
this.left.midList();
}
System.out.println(this);
if (this.right != null){
this.right.midList();
}
}
}
二叉排序树的创建与添加
最新推荐文章于 2024-09-25 11:06:23 发布