版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
二叉树(java)
数组实现
//数组实现二叉树
public class ArrayTree <T>{
private T[] data;
private int deep;
private int MaxSize;
private int size=0;
public ArrayTree(int deep) {
this.deep=deep;
MaxSize=(int)Math.pow(2,deep)-1;
data=(T[])new Object[MaxSize];
}
public void creatRoot(T value) {
data[0]=value;
size++;
}
public void add(T value,int index,boolean left) {
if(data[index]==null) {
throw new RuntimeException(index+":null");
}
if(2*index+1>=MaxSize) {
throw new RuntimeException("array full");
}
if(left) {
data[2*index+1]=value;
size++;
}else {
data[2*index+2]=value;
size++;
}
}
public boolean inEmpty() {
return data[0]==null;
}
public int size() {
return this.size;
}
public String toString() {
String str="";
for(int i=0;i<MaxSize;i++) {
str=str+data[i]+" ";
}
return str;
}
public static void main(String[] args) {
ArrayTree<String> tree=new ArrayTree<String>(3);
tree.creatRoot("A");
tree.add("B", 0, true);
tree.add("C", 0, false);
tree.add("E", 1, false);
tree.add("G", 2, true);
tree.add("H", 2, false);
System.out.println(tree.toString());
System.out.println(tree.size);
}
}
运行结果:
链表实现
import java.util.ArrayList;
import java.util.List;
public class NodeTree<T> {
class Node<T>{
public Node left;//左子树
public Node right;//右子树
public T data;
public Node(T data) {
this.data=data;
this.left=null;
this.right=null;
}
public Node() {};
}
private Node root;
private int size=0;
public void createRoot(T value) {
if(value==null) {
throw new RuntimeException("root is null");
}
Node<T> newNode=new Node<T>(value);
this.root=newNode;
size++;
}
public Node getRoot() {
if(root==null) {
throw new RuntimeException("root is null");
}
return this.root;
}
public boolean isEmpty() {
return root==null;
}
public Node add(Node<T> n,T value,boolean left) {
if(value==null) {
throw new RuntimeException("子节点为空");
}
if(n==null) {
throw new RuntimeException("父节点为空");
}
Node<T> newNode=new Node<T>(value);
if(left) {
if(n.left!=null) {
throw new RuntimeException("已有左子节点");
}
n.left=newNode;
size++;
return newNode;
}else {
if(n.right!=null) {
throw new RuntimeException("已有子右节点");
}
n.right=newNode;
size++;
return newNode;
}
}
public static void main(String[] args) {
NodeTree<String> tree=new NodeTree();
tree.createRoot("A");
NodeTree.Node node1=tree.add(tree.root, "B",true);
NodeTree.Node node2=tree.add(tree.root, "C",false);
NodeTree.Node node3=tree.add(node1, "D",false);
NodeTree.Node node4=tree.add(node2, "E",true);
NodeTree.Node node5=tree.add(node2, "F",true);
}
}