我知道递归中序遍历的空间复杂度是O(h),而不是O(n),其中h是树的高度,n是树中节点的数量。
为什么会这样呢?比如说,这是遍历代码:
public void inorderPrint (TreeNode root) {
if (root == null) {
return;
}
inorderPrint(root.left);
System.out.println(root.data);
inorderPrint(root.right);
}
我们将n个内存地址推入调用栈,因此空间复杂度应为O(n)。
我漏掉了什么?
preorderPrint
。 - John Coleman