java-二叉树源码

package cn.ml.comparable;
//二叉树
class BinaryTree<T extends Comparable<T>>{
private class Node{ //只要是进行数据结构的开发,必然要存在有node类对象
private T data; //保存的数据类型由外部来统一设置
private Node left;
private Node right;
public Node(T data) {
this.data = data;
}
public void addNode(Node newNode) {
Comparable<T> comp = newNode.data; //取出原始的保存对象
if(comp.compareTo(this.data)<0) { //判断节点间数据关系
if(this.left == null) { //左子树为空,可以保存
this.left = newNode;
}else {
this.left.addNode(newNode); //向左边继续进行判断
}
}else {
if(this.right ==null) {
this.right = newNode;
}else {
this.right.addNode(newNode);
}
}
}
public  void toArrayNode() {
if(this.left !=null) {
this.left.toArrayNode();
}
BinaryTree.this.retData[BinaryTree.this.foot ++] =this.data;
if(this.right !=null) {
this.right.toArrayNode();
}
}
}
//======================================================
private Node root; //根节点是关键性节点,第一个数据应该设置为根节点
private int count; //保存元素的个数
private Object[] retData;
private int foot =0;
public void add(T data) { //设置要保存的数据
if(!(data instanceof Comparable)) {
throw new ClassCastException("当前传入的对象不是Comparable接口子类");
}
//为了进行节点的关系处理,此处必须要将数据包装为Node类对象
Node newNode = new Node(data);
if(this.root ==null) { //如果现在根节点没有数据
this.root = newNode;
}else {
this.root.addNode(newNode);
}
this.count ++;
}
/**
* 返回全部的二叉数数据
* @return
*/
public Object[] toArray() {
if(this.count ==0) {
return null ; //现在没有数据
}
this.foot = 0; //重置脚标
this.retData = new Object[this.count]; //开辟数组
this.root.toArrayNode();
return this.retData;
}
}

public class TextComparable1 {


public static void main(String[] args) {
BinaryTree<Manber> bt= new BinaryTree<Manber>();
bt.add(new Manber("萌系",18));
bt.add(new Manber("梦与",20));
bt.add(new Manber("夏雨",19));
Object [] temp = bt.toArray();
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
}
}
class Manber implements Comparable<Manber>{
private String name;
private int age;
public Manber() {};
public Manber(String name,int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "name : = "+ this.name + "age := " + age;
}
@Override
public int compareTo(Manber o) {


return this.age -o.age;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值