二叉树的创建

import java.util.*;
public class Tree{
    static LinkedList<Node> nodelist = null;
    class Node{
        Node left;
        Node right;
        int data;
        public Node(int data){
            this.data = data;
        }
    }
    public void createTree(int[] array){
         nodelist = new LinkedList<Node>();
        for(int i=0;i<array.length;i++){
            Node n = new Node(1);
            nodelist.add(new Node(array[i]));
        }
        for(int i=0;i<array.length/2-1;i++){
            nodelist.get(i).left = nodelist.get(i*2+1);
            nodelist.get(i).right = nodelist.get(i*2+2);
        }
        int lastIndex = array.length/2-1;
        nodelist.get(lastIndex).left = nodelist.get(lastIndex*2+1);
        if(array.length%2==1){
            nodelist.get(lastIndex).right = nodelist.get(lastIndex*2+2);
        }
    }
    public void preOrderTraverse(Node node){
        if(node == null) return ;
        System.out.println(node.data);
        preOrderTraverse(node.left);
        preOrderTraverse(node.right);
    }
    public static void main(String[] args){
        int[] array = {4,3,5,6,2,9,1};
        Tree t = new Tree();
        t.createTree(array);
        t.preOrderTraverse(nodelist.get(0));
    }
}

1. 父节点数组下标从0到 n/2 -1 ,但是遍历时要小于n/2-1,因为最后一个父节点可能没有右孩子,当n/2-1为奇数时才有右孩子,为偶数时只有左孩子。

2. 结点左孩子下标为2n+1,右孩子下标为2n+2。

posted @ 2018-07-05 23:03  樱圃  阅读(175)  评论(0编辑  收藏  举报