gpt4 book ai didi

java - 二叉树到数组的中序排序

转载 作者:行者123 更新时间:2023-12-01 12:08:19 25 4
gpt4 key购买 nike

我正在尝试以降序方式遍历二叉树并将元素复制到数组中。我相信我已经完成了 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);
}

最佳答案

尝试更新 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;
}

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

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