【问题标题】:Why is the time complexity of this function to check the balance of a Binary Tree O(n log n)?为什么这个函数检查二叉树平衡的时间复杂度是 O(n log n)?
【发布时间】:2020-01-23 22:11:46
【问题描述】:

Gayle Laakmann McDowell 对 Coding 采访的提示:

实现一个函数来检查二叉树是否平衡。 对于这个问题,定义了一个平衡树,使得高度 任何节点的两个子树的差异不超过一个。

(下面的示例实现。)

问题:你能帮我理解为什么作者说isBalanced有一个 O(n log n) 的时间复杂度?我在某种程度上可以理解并且可以很好地记住这一点,但我无法像O(n^2)这样的其他时间复杂性那样概念化为什么会出现这种情况。

int getHeight(TreeNode root) {
  if (root == null) { return -1; }
  return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}

boolean isBalanced(TreeNode root) {
  if (root == null) { return true; }

  int heightDiff = getHeight(root.left) - getHeight(root.right);
  if (Maths.abs(heightDiff) > 1) {
    return false;
  } else {
    return isBalanced(root.left) && isBalanced(root.right);
  }
}

// isBalanced([some node]) --> true/false

我如何想象为什么isBalanced 被视为O(n log n)

【问题讨论】:

标签: java time-complexity binary-tree big-o logarithm


【解决方案1】:

假设你有 BST

      4        // No of nodes 1
    /    \
   2      6    // No of nodes 2
 /  \    /  \
1    3  5    7 // No of nodes 4

您的函数isBalanced 正在遍历所有节点,包括没有子节点的节点,并调用getHeight 来计算左右子节点的高度。

函数的递归关系是

源于主定理

a = 递归子问题的数量

n/b = 每个子问题的大小

f(n) = 必须在递归调用之外完成的工作成本

a2 因为我们必须访问每个父节点的两个子节点

b2,因为如果您注意到每次上一层(从底部开始),节点数量都会减少一半。

f(n)n 因为我们必须在每个节点上调用 getHeight()

满足Master Theorem的第二种情况,即

用数值证明f(n) = O(n^logb(a))

因此我们得到O(n log n)的时间复杂度

【讨论】:

  • 我认为这不能回答问题。他的问题是为什么时间复杂度是 O(n log n) 而不是他预期的 O(n^2)。
  • @0x499602D2 这可以接受吗?感谢您指出我的错误。
猜你喜欢
  • 1970-01-01
  • 2019-12-21
  • 2021-11-11
  • 2022-10-24
  • 2011-07-09
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多