按顺序将二叉树排序为数组

时间:2014-12-11 09:27:06

标签: java binary-tree

我试图以降序的方式遍历二叉树并将元素复制到数组中。我相信我80%在那里,我似乎无法弄清楚我的索引发生了什么。任何有关正确方向的帮助或指示都会受到赞赏。

public static void inorder(int[] a) {
    int i = 0;

    // call recursion
    inorder(root, a, i);


    System.out.println("Array: ");
    for (int j = 0; j < a.length; j++) {
        System.out.println(a[j]);
    }
}

private static void inorder(Node temp, int[] a, int i) {
    // base case
    if (temp == null) return;

    // go to the right of tree
    inorder(temp.right, a, i);


    // copy node to array
    a[i] = temp.number;
    System.out.println(temp.number);
    System.out.println(i);
    i++;

    // go to the left of tree
    inorder(temp.left, a, i);
}  

1 个答案:

答案 0 :(得分:1)

尝试更新i并返回其值

private static int inorder(Node temp, int[] a, int i) {
// base case
if (temp == null) return i;

// go to the right of tree
i = inorder(temp.right, a, i);


// copy node to array
a[i] = temp.number;
System.out.println(temp.number);
System.out.println(i);
i++;

// go to the left of tree
i = inorder(temp.left, a, i);
return i;
}