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

标签 java algorithm data-structures time-complexity callstack

所以这个程序决定了一个btree的对称性。 令我困惑的是 checkSymmetric 在同一行中被调用了两次。那么这是否意味着我们必须为每次调用 checkSymmetric 向调用堆栈添加两个新的堆栈帧?如果是这样的话,我们不应该有 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;
}

最佳答案

请注意,我们会提供帮助,但实际上我们不会为您做功课。

What is confusing me is that checkSymmetric is called twice in the same line. So wouldnt that mean we have to add two new stack frames to our callstack for each call to checkSymmetric?

不是,因为这两个调用是顺序的,不是并行的。根据定义,在第二次调用之前释放一次调用执行范围内的所有资源——它们并非同时持有。这当然包括所有涉及的堆栈帧。

If thats the case shouldnt we have O(2^h) space complexity?

事实并非如此,那么关于空间复杂度,这说明了什么?

关于java - 为什么这个程序的空间复杂度是O(h)?其中 h 是 btree 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46457771/

相关文章:

performance - 使用倒排索引对搜索结果进行排名的有效方法

algorithm - 从给定的数字中,确定三个相近的数字,其乘积是原始数字

data-structures - r5rs 中的哈希表

algorithm - 如何输出无向图的所有双连通分量?

c++ - 用于存储和访问结构指针的正确 Qt 数据结构

java - ResultSet.get 抛出 java.sql.SQLException : Invalid operation at current cursor position

java - 如何将 SOAP 操作添加到 java 中的 web 服务?

java - 如何保存包含其他实体列表的 JPA/Spring Data 实体,而不必全部查找?

php - 独特值的 SQL 查询(条目)

java - 如何使用相对路径在项目文件中使用 FileWriter 创建文件