java - 将二叉树存储到数组中

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

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

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], 而且它也不按顺序。

我不知道我做错了什么。如有任何帮助,我们将不胜感激。

最佳答案

您没有使用返回值。而且您需要使用它,因为 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;
}

关于java - 将二叉树存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47125279/

相关文章:

java - 套接字 mac os x vs windows java 慢

php - 比较相同的数组值

java - 无法将文件放入 Java 字节数组

algorithm - 遍历二叉树

c++ - 二叉树 getParent 函数

prolog - 使用 Prolog 获取所有可能的二叉树?

java - Android 使用位置管理器获取纬度和经度

java - 当将数据结构声明为其接口(interface)然后对其进行强制转换时,Java 是否将详细信息存储在某处

java - 行为或 Java 数组

javascript - 选择一个随机的 json 对象