package com.example.demo;
import java.util.Arrays;
public class ErChaShu {
public static void main(String[] args) {
BinaryTree<Person1> tree = new BinaryTree<>();
tree.add(new Person1("A", 80));
tree.add(new Person1("B", 70));
tree.add(new Person1("C", 50));
tree.add(new Person1("D", 90));
tree.add(new Person1("E", 10));
tree.add(new Person1("F", 20));
System.out.println(Arrays.toString(tree.toArray()));
}
}
/**
* 实现二叉树操作
* @param <T> 要进行二叉树的实现
*/
class BinaryTree<T extends Comparable<T>>{
private class Node{
private Comparable<T> data; //存放Comparable,可以比较大小
private Node parent;
private Node left;
private Node right;
public Node(Comparable<T> data){
this.data = data;
}
/**
* 实现节点数据的实当位置的存储
* @param newNode 创建新的节点
*/
public void addNode(Node newNode){
if(newNode.data.compareTo((T)this.data) <= 0){
if(this.left == null){
this.left = newNode;
newNode.parent = this;
}else {
this.left.addNode(newNode);
}
}else {
if(this.right == null){
this.right = newNode;
newNode.parent = this;
}else {
this.right.addNode(newNode);
}
}
}
/**
* 实现所有数据的获取处理,按照中序遍历来形式来完成
*/
public void toArrayNode(){
if(this.left != null){
this.left.toArrayNode();
}
BinaryTree.this.returnData[BinaryTree.this.foot ++] = this.data;
if(this.right != null){
this.right.toArrayNode();
}
}
}
//二叉树功能实现
private Node root; //保存跟节点
private int count; //保存数据个数
private Object[] returnData; //返回的数据
private int foot = 0; //脚标控制
/**
* 进行数据的保存
* @param data
*/
public void add(Comparable<T> data){
if(data == null){
throw new NullPointerException("保存的数据不允许为空!");
}
//所有的数据本身不具备有节点关系的匹配,那么一定要将其包装在Node类之中
Node newNode = new Node(data);
if(this.root == null){
this.root = newNode;
}else {
this.root.addNode(newNode);
}
this.count++;
}
/**
* 以对象数组的形式返回全部数据,如果没有则返回null
* @return
*/
public Object[] toArray(){
if(this.count == 0){
return null;
}
this.returnData = new Object[this.count];
this.foot = 0;
this.root.toArrayNode();
return this.returnData;
}
}
class Person1 implements Comparable<Person1>{
private String name;
private int age;
public Person1(String name, int age){
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person1 o) {
return this.age - o.age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
二叉树的构造
最新推荐文章于 2024-02-05 17:42:06 发布