完全二叉树的构建
创建MyNode<E>类,添加到LinkedList里,用循环添加左右孩子
n=节点个数,i=节点序号(从0开始)
父节点个数=n/2(取整,小数点省略)
左孩子:2*i+1<n
右孩子:2*i+2<n
遍历代码
package BinaryTree;
import java.util.LinkedList;
public class BinaryTree {
public LinkedList<MyNode<Integer>> list = new LinkedList<MyNode<Integer>>();
int[] arry = {1,2,3,4,5,6,7,8,9};
public void genParent(){
for (int i = 0; i < arry.length; i++) {
MyNode<Integer> myNode = new MyNode<Integer>(null,arry[i],null);
list.add(myNode);
}
}
public void genTree(){
for (int i = 0; i < list.size()/2; i++) {
MyNode<Integer> myNode = list.get(i);
if((2*i+1) < list.size()){
myNode.leftchild = list.get(2*i+1);
}
if((2*i+2) < list.size()){
myNode.rightchild = list.get(2*i+2);
}
}
}
public void pre(MyNode<Integer> root){
if(root == null)
return;
System.out.print(root.e+" ");
pre(root.leftchild);
pre(root.rightchild);
}
public void mid(MyNode<Integer> root){
if(root == null)
return;
mid(root.leftchild);
System.out.print(root.e+" ");
mid(root.rightchild);
}
public void behind(MyNode<Integer> root){
if(root == null)
return;
behind(root.leftchild);
behind(root.rightchild);
System.out.print(root.e+" ");
}
}