【问题标题】:Storing Binary Tree into an array将二叉树存储到数组中
【发布时间】:2017-11-06 02:58:56
【问题描述】:

我尝试使用以下代码将二叉树存储到数组中:

public void inorderArray(int[] array)  {
       inorderArray(root, array, 0);
}

private static Integer inorderArray(TreeNode root, int[] array, int index) { 
    // an inorder traversal that stores the items in array
    if(root == null){return index;}

    inorderArray(root.left, array, index);
    array[index++] = root.key;
    inorderArray(root.right, array, index);

    return index;
}

我不断收到[94, 95, 0, 0, 0, 0, 0, 0, 0, 0], 而且它也不按顺序。

我不知道我做错了什么。任何帮助表示赞赏。

【问题讨论】:

  • 附带说明 - 无需返回 Integer,只需 int 就足够了。

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


【解决方案1】:

您没有使用返回值。而且你需要使用它,因为index++中的修改永远不会离开函数的范围。

private static int inorderArray(TreeNode root, int[] array, int index) {
    if (root == null) {
        return index;
    }

    index = inorderArray(root.left, array, index);
    array[index++] = root.key;
    index = inorderArray(root.right, array, index);
    return index;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-05
    • 2023-03-18
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    相关资源
    最近更新 更多