3_BinaryTree(二叉树)
1.如果以数据结构为例: 会使用递归,数组操作, 链表, 树, 图
2.对于树的擦欧总需要考虑两个问题
一个数据的存储问题: 左(Node), 右(Node)
另外一个就是树的遍历问题:前序, 中序, 后序的问题
3.如果要进行二叉树的操作处理, 往往要使用中序, 因为中序可以排序。在实现二叉树的时候, 必须要考虑对象的大小关系的比较问题, 正因为需要考虑大小关系, 所以数据的存储应该以Comparable为主
import java.util.Arrays;
class BinaryTree{
//树之中需要保存数据以及各个节点之间的关系
private class Node{ //只是做一个数据的载体, 好确认关系
private Comparable data;
private Node left;
private Node right;
public Node(Comparable data){
this.data = data;
}
public void toArrayNode(){
if(this.left != null)
{
this.left.toArrayNode();
}
BinaryTree.this.retObj[BinaryTree.this.foot++ ] = this;
if(this.right != null)
{
this.right.toArrayNode();
}
}
public void addNode(Node newNode)
{
if(this.data.compareTo(newNode.data)<0)
{
if(this.right == null)
{
this.right = newNode;
}
else
{
this.right.addNode(newNode);
}
}else{
if(this.left == null)
{
this.left = newNode;
}else{
this.left.addNode(newNode);
}
}
}
}
//**************************
private Node root; //需要根节点
private int count; //统计个数
private int foot = 0;
private Object retObj[];
public Object[] toArray(){
if(this.root == null)
{
return null;
}
this.retObj = new Object[this.count];
this.root.toArrayNode();
return retObj;
}
public void add(Object data){
Comparable com = (Comparable) data;
Node newNode = new Node(com); //设置节点是为了排序
if(this.root == null) //表示现在没有根节点
{
this.root = newNode;
}else { //需要交给Node处理, 考虑大小关系比较
this.root.addNode(newNode);
}
this.count++;
}
}
public class TestBinaryTree {
public static void main(String [] args)
{
BinaryTree bt = new BinaryTree();
bt.add(“B”);
bt.add(“C”);
bt.add(“I”);
bt.add(“H”);
bt.add(“A”);
System.out.println(Arrays.toString(bt.toArray()));
}
}