二叉树的基础实现 代码
Posted yxj808
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的基础实现 代码相关的知识,希望对你有一定的参考价值。
class BinaryTree <T extends Comparable<T>>{
private class Node{
private Comparable<T> data;//可以比较大小
private Node parent;//保存父节点
private Node left;
private Node right;
public Node(Comparable<T> data) {
this.data=data;
}
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=0;
private Object[] returnData;//返回的数据
private int foot =0;
public void add(Comparable<T> data) {
if(data==null) {
throw new NullPointerException("保存的数据不能为空");
}
Node newNode=new Node(data);
if(this.root==null) {
this.root=newNode;
}else {
this.root.addNode(newNode);
}
this.count++;
}
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 Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
@Override
public int compareTo(Person per) {
return this.age-per.age;
}
public String toString() {
return "【Person对象】姓名"+this.name+"年龄"+this.age+"
";
}
}
public class Test1 {
public static void main(String[] args) throws Exception {
BinaryTree<Person> tree = new BinaryTree<Person>();
Person p1 = new Person("zhangsan", 32);
Person p2 = new Person("lili", 47);
Person p3 = new Person("lisi", 93);
Person p4 = new Person("wangwu", 12);
Person p5 = new Person("xiaoming", 38);
tree.add(p1);
tree.add(p2);
tree.add(p3);
tree.add(p4);
tree.add(p5);
System.out.println(Arrays.toString(tree.toArray()));
}
}
以上是关于二叉树的基础实现 代码的主要内容,如果未能解决你的问题,请参考以下文章