顺序化二叉树
/**
* 顺序化二叉树:使用数组存储二叉树
*/
public class OrderBinaryTree {
private Integer[] orderBinaryTree = new Integer[] {1, 2, 3, 4, 5};
public static void main(String[] args) {
OrderBinaryTree orderBinaryTree = new OrderBinaryTree();
orderBinaryTree.preOrder(0);
System.out.println("------------");
orderBinaryTree.midOrder(0);
System.out.println("------------");
orderBinaryTree.postOrder(0);
}
public void preOrder(int index) {
System.out.println(orderBinaryTree[index]);
if ((index * 2 + 1 < orderBinaryTree.length) && orderBinaryTree[index * 2 + 1] != null) {
preOrder(index * 2 + 1);
}
if ((index * 2 + 2 < orderBinaryTree.length) && orderBinaryTree[index * 2 + 2] != null) {
preOrder(index * 2 + 2);
}
}
public void midOrder(int index) {
if ((index * 2 + 1 < orderBinaryTree.length) && orderBinaryTree[index * 2 + 1] != null) {
midOrder(index * 2 + 1);
}
System.out.println(orderBinaryTree[index]);
if ((index * 2 + 2 < orderBinaryTree.length) && orderBinaryTree[index * 2 + 2] != null) {
midOrder(index * 2 + 2);
}
}
public void postOrder(int index) {
if ((index * 2 + 1 < orderBinaryTree.length) && orderBinaryTree[index * 2 + 1] != null) {
postOrder(index * 2 + 1);
}
if ((index * 2 + 2 < orderBinaryTree.length) && orderBinaryTree[index * 2 + 2] != null) {
postOrder(index * 2 + 2);
}
System.out.println(orderBinaryTree[index]);
}
}
|