gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:45 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com