1 用二叉排序树存储
2 层次遍历需要用队列 先把跟放到队列中,然后出队一个同时将其左右child分别入队,知道队空
import java.util.ArrayList;
import java.util.List;
/**
* 1 有序数组放入到树中,二叉排序树
* 2 层次遍历这个树
* @author Acer
*
*/
public class TreeLayerAccess {
public static void main(String[] args) {
/*
int[] a = {5,3,9,1,7,2,8};
TaNode root = null;
for(int i =0;i<a.length;i++){
root = add(root, a[i]);
}
midAccess(root);
*/
TaNode root = null;
int[] a =new int[]{1,2,3,4,5,6,7,8,9};
root = OderArrayInsertIntoTree(root, a, 0, a.length-1);
//midAccess(root);
layerAccess(root);
}
public static void layerAccess(TaNode root){
if(root == null)
return;
List<TaNode> queue = new ArrayList<TaNode>();
System.out.println(queue.size());
queue.add(root);
while(queue.size()!=0){
TaNode node = queue.remove(0);
System.out.print(node.value+" ");
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
}
/**
* 有序数组放入到树中,二叉排序树
* @param root
* @param a
* @param begin
* @param end
* @return
*/
public static TaNode OderArrayInsertIntoTree(TaNode root, int[] a , int begin ,int end){
if(begin<=end){
int mid = (begin+end)/2;
root= add(root, a[mid]);
OderArrayInsertIntoTree(root, a, begin, mid-1);
OderArrayInsertIntoTree(root, a, mid+1, end);
}
return root;
}
public static TaNode add(TaNode root , int value){
if(root==null){
return new TaNode(value);
}
else{
if(value<root.value){
if(null == root.left){
root.left = new TaNode(value);
}
else{
add(root.left, value);
}
}
else{
if(null == root.right){
root.right = new TaNode(value);
}
else{
add(root.right, value);
}
}
return root;
}
}
public static void midAccess(TaNode root ){
if(root!=null){
midAccess(root.left);
System.out.print(root.value);
midAccess(root.right);
}
}
}
class TaNode{
public TaNode(int value){
this.value = value;
}
public int value;
public TaNode left;
public TaNode right;
}