把一个数组的值存入二叉树中,然后进行3种方式的遍历(完整代码)

功能:把一个数组的值存入二叉树中,然后进行3种方式的遍历

package unit5__BiTree;  

import java.util.LinkedList;
import java.util.List;

public class ListTreeTest { 
    private int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    private static List nodeList = null;
    private static class Node {
        Node leftChild;
        Node rightChild;
        int data;
        Node(int newData){
            leftChild = null;
            rightChild = null;
            data = newData;
        }
    }
    public void createBinTree(){
        nodeList = new LinkedList();
        for(int nodeIndex = 0; nodeIndex < array.length; nodeIndex++){
            nodeList.add(new Node(array[nodeIndex]));
        }
        for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
            nodeList.get(parentIndex).leftChild = nodeList.get(parentIndex*2+1);
            nodeList.get(parentIndex).rightChild = nodeList.get(parentIndex*2+2);
        }
        int lastParentIndex = array.length / 2-1;
        nodeList.get(lastParentIndex).leftChild = nodeList.get(lastParentIndex*2+1);
        if (array.length % 2 == 1) {
            nodeList.get(lastParentIndex).rightChild = nodeList.get(lastParentIndex*2+2);
        }
    }
    //前序遍历
    public static void preOrderTraverse(Node node) {
        if (node == null) {
            return;
        }
        System.out.print(node.data+" ");
        preOrderTraverse(node.leftChild);
        preOrderTraverse(node.rightChild);
    }
    //中序遍历 
    public static void inOrderTraverse(Node node) {  
        if (node == null)  
            return;  
        inOrderTraverse(node.leftChild);  
        System.out.print(node.data + " ");  
        inOrderTraverse(node.rightChild);  
    }  
    //后序遍历  
    public static void postOrderTraverse(Node node) {  
        if (node == null)  
            return;  
        postOrderTraverse(node.leftChild);  
        postOrderTraverse(node.rightChild);  
        System.out.print(node.data + " ");  
    }  
    public static void main(String[] args) {
        ListTreeTest binTree = new ListTreeTest();  
        binTree.createBinTree();  
        // nodeList中第0个索引处的值即为根节点  
        Node root = nodeList.get(0);  

        System.out.println("先序遍历:");  
        preOrderTraverse(root);  
        System.out.println();  

        System.out.println("中序遍历:");  
        inOrderTraverse(root);  
        System.out.println();  

        System.out.println("后序遍历:");  
        postOrderTraverse(root);  
    }
}  

递归逐步遍历二叉树。

你可能感兴趣的:(把一个数组的值存入二叉树中,然后进行3种方式的遍历(完整代码))