从数组创建一个平衡的二叉树,尝试着色地做,但不断创建一个不平衡的树?

时间:2016-11-07 19:57:04

标签: java arrays tree binary-tree binary-search-tree

getAlphabet()是a-z的字母数组。我正在尝试按照级别顺序从数组中填充树。所以root是a,孩子是b,c。然后b孩子们,是吗?

public static void makeTree(String[] alphabet){

    TreeNode<String> root0 = new TreeNode<String>(null);
    TreeNode<String> tempRoot = root0;
    TreeNode<String> tempRoot1 = root0;

    for(int i = 0; i<getAlphabet().length; i++){
        if(2*i+1 < getAlphabet().length-1) {
            tempRoot.setLeftChild(new TreeNode<String>(getAlphabet()[2 * i + 1], tempRoot));
            tempRoot.setRightChild(new TreeNode<String>(getAlphabet()[2 * (i + 1)], tempRoot));

            tempRoot = tempRoot.getLeftChild();
            tempRoot1 = tempRoot.getRightChild();
        }


    }





    // create the Tree as a linked structure from the arrayS myStringChars
    // the Strings are stored using the representation for trees as arrays in the book
    // (e.g. for an element i, the left child is stored in position 2*i + 1, right child is
}

0 个答案:

没有答案