/**
* @author lpc
* @create 2020-09-02-10:18
*/
public class Tree<T extends Comparable<T>>{
private Node root;//根节点
private int size;
public Tree(){}
/* 通过数组构造 */
public Tree(T[] arrays){
for(T t:arrays){
add(t);
}
}
public void add(T data){
Node newNode=new Node(data);
if(root==null)
root=newNode;//如果根节点为空,就承认
else
root.addNode(newNode);
size++;
}
/* 打印 */
public void printf(){root.printf();}
/* 长度 */
public int size(){return size;}
private int index;
/* 输出为数组 */
public Object[] getArrays(){
index=0;
Object[] arrays=new Object[size];
root.toArrays(arrays);
return arrays;
}
/* 节点 */
class Node{
private final T data;//当前节点
private Node left;//左
private Node right;//右
public Node(T data){this.data=data;}
public T getData() { return data; }
/* 在当前节点添加 */
public void addNode(Node newNode){
//新加入的比当前小,放到左子树
if(newNode.data.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 printf(){
if(this.left!=null)
this.left.printf();//先找左边的节点
System.out.println(this.data+"\t");//输出当前节点
if(this.right!=null)
this.right.printf();//如果右边还有,就输出
}
public void toArrays(Object[] arrays){
if(this.left!=null)//左边还有,就向左边
this.left.toArrays(arrays);
arrays[index]=this.data;//将当前添加到数组
index++;//指针右移
if(this.right!=null)//右边还有,继续添加
this.right.toArrays(arrays);
}
}
}
java实现简易的排序二叉树并输出数组
最新推荐文章于 2024-03-16 22:05:56 发布