我尝试使用以下代码将二叉树存储到数组中:
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/