构建二叉树 遍历二叉树
数组法构建二叉树
public class Main {
static LinkedList<Tree> linkedList=new LinkedList<Tree>();
static int[] a= {1,2,3,4,5,6,7,8,9};
public static void main(String[] args) {
createBinTree();
//获取链表的头结点
Tree root=linkedList.get(0);
System.out.println("先序遍历:");
preOrder(root);
System.out.println();
System.out.println("中序遍历:");
inOrder(root);
System.out.println();
System.out.println("后序遍历:");
postOrder(root);
System.out.println();
}
//用数组的方式构建二叉树
public static void createBinTree() {
//把数组中的值转为二叉树的值并存入LinkedKist集合
for(int i=0;i<a.length;i++) {
linkedList.add(new Tree(a[i]));
}
//把LinkedList集合转成二叉树的形式
for(int j=0;j<a.length/2-1;j++) {
linkedList.get(j).leftTree=linkedList.get(j*2+1);
linkedList.get(j).rightTree=linkedList.get(j*2+2);
}
//最后一个父节点单独计算
int lastTree=a.length/2-1;
linkedList.get(lastTree).leftTree=linkedList.get(lastTree*2+1);
//数组元素个数是奇数则最后一个父节点有右孩子
if(a.length%2==1) {
linkedList.get(lastTree).rightTree=linkedList.get(lastTree*2+2);
}
}
//先序遍历
public static void preOrder(Tree tree) {
if(tree!=null) {
System.out.print(tree.data);
preOrder(tree.leftTree);
preOrder(tree.rightTree);
}
}
//中序遍历
public static void inOrder(Tree tree) {
if(tree!=null) {
inOrder(tree.leftTree);
System.out.print(tree.data);
inOrder(tree.rightTree);
}
}
//后序遍历
public static void postOrder(Tree tree) {
if(tree!=null) {
postOrder(tree.leftTree);
postOrder(tree.rightTree);
System.out.print(tree.data);
}
}
}
class Tree{
int data;
Tree leftTree;
Tree rightTree;
public Tree(int data) {
this.data=data;
}
}