简体   繁体   English

为什么该程序的空间复杂度为O(h)? 其中h是btree的高度

[英]Why is the space complexity of this program O(h)? Where h is height of btree

So this program determines the symmetry of a btree. 因此,该程序确定btree的对称性。 What is confusing me is that checkSymmetric is called twice in the same line. 令我感到困惑的是,在同一行中两次调用了checkSymmetric。 So wouldnt that mean we have to add two new stack frames to our callstack for each call to checkSymmetric? 那么这是否意味着对于每个checkSymmetric调用,我们都必须向我们的调用堆栈中添加两个新的堆栈框架? If thats the case shouldnt we have O(2^h) space complexity? 如果是这样的话,我们是否具有O(2 ^ h)空间复杂度?

public static boolean isSymmetric(BinaryTreeNode<Integer> tree) {
return tree == null || checkSymmetric(tree.left, tree.right);
}

private static boolean checkSymmetric(BinaryTreeNode<Integer> subtree0,
                                    BinaryTreeNode<Integer> subtree1) {
if (subtree0 == null && subtree1 == null) {
  return true;
} else if (subtree0 != null && subtree1 != null) {
  return subtree0.data == subtree1.data
      && checkSymmetric(subtree0.left, subtree1.right)
      && checkSymmetric(subtree0.right, subtree1.left);
}
// One subtree is empty, and the other is not.
return false;
}

Note that we'll help, but we won't actually do your homework for you. 请注意,我们会提供帮助,但实际上不会为您做作业。

What is confusing me is that checkSymmetric is called twice in the same line. 令我感到困惑的是,在同一行中两次调用了checkSymmetric。 So wouldnt that mean we have to add two new stack frames to our callstack for each call to checkSymmetric? 那么这是否意味着对于每个checkSymmetric调用,我们都必须向我们的调用堆栈中添加两个新的堆栈框架?

No, because the two calls are sequential, not parallel. 否,因为这两个调用是顺序的,而不是并行的。 All resources scoped to the execution of one call are, by definition, released before the second call -- they are not all held at the same time. 根据定义,所有用于执行一次调用的资源都在第二次调用之前释放-它们不会同时保留。 That certainly includes all the stack frames involved. 这当然包括所有涉及的堆栈框架。

If thats the case shouldnt we have O(2^h) space complexity? 如果是这样的话,我们是否具有O(2 ^ h)空间复杂度?

It is not the case, so what does that tell you about the space complexity? 事实并非如此,那么这能告诉您关于空间复杂性的什么信息?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM