1.定义节点类:
public class Node<T> {
public Node<T> parent;
public Node<T> leftChild;
public Node<T> rightChild;
public T value;
}
2.定义构建满二叉树类
public class FullBiTree {
/**
* 递归创建满二叉树
* @param n 二叉树层数
* @param index 序数值
* @return
*/
public static Node<Integer> buildFullBiTree(int n,int index){
Node<Integer> node=new Node<Integer>();
node.value = index;
if(n==1){
return node;
}
else{
Node<Integer> leftNode=buildFullBiTree(n-1,2*index);
leftNode.parent=node;
node.leftChild=leftNode;
Node<Integer> rightNode=buildFullBiTree(n-1,2*index+1);
rightNode.parent=node;
node.rightChild=rightNode;
}
return node;
}
}
3: 深度优先遍历二叉树
/**
* 深度优先遍历满二叉树
* @param root
*/
public static void dftFullBiTree(Node root){
if(root!=null){
System.out.print (root.value+"--");
dftFullBiTree(root.leftChild);
dftFullBiTree(root.rightChild);
}
}
4: 广度优先遍历二叉树
/**
* 广度优先遍历满二叉树
* @param root
*/
public static void bftFullBiTree(Node root){
List<Node> parentList=new ArrayList<Node>();
List<Node> childList=new ArrayList<Node>();
int index=1;
parentList.add(root);
while(!parentList.isEmpty()){
for(int m=0;m<parentList.size();m++){
Node parent=parentList.get(m);
if(parent.leftChild!=null) {
childList.add(parent.leftChild);
}
if(parent.rightChild!=null) {
childList.add(parent.rightChild);
}
System.out.print(parent.value+"--");
}
parentList.clear();
parentList=childList;
childList=new ArrayList<Node>();
}
System.out.println("");
}
5: 运行
public static void main(String[] arg){
int n=4;
Node<Integer> biTree= buildFullBiTree(n,1);
bftFullBiTree(biTree);
dftFullBiTree(biTree);
}