【问题标题】:Maximum Depth of Binary Tree二叉树的最大深度
【发布时间】:2016-01-24 07:27:29
【问题描述】:
public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        else
        return (maxDepth(root.left)>maxDepth(root.right))?(maxDepth(root.left)+1):(maxDepth(root.right)+1);
    }
}

它返回超过时间限制。我想知道为什么会发生这种情况,我的代码有什么问题?

【问题讨论】:

  • 使用主定理并假设树是平衡的,运行时间在Omega(n^1.58),但你可以达到O(n)(除非我忽略了一些其他错误)

标签: java recursion tree


【解决方案1】:

你真的很亲密。我认为您的目标是:

int maxHeight(TreeNode p) {
  if (p == null) return 0;
  int leftHeight = maxHeight(p.left);
  int rightHeight = maxHeight(p.right);
  return (leftHeight > rightHeight) ? leftHeight + 1 : rightHeight + 1;
}

我认为您超过时间限制的原因是因为您的递归调用比您需要的要多得多。为了解决这个问题,你只需要计算左子树的大小,右子树的大小,并返回两个值中较大的一个+1(对于根)。

【讨论】:

  • 非常感谢!现在我知道我已经多次使用递归了。我应该每次使用它两次!
【解决方案2】:

很难想象大多数二叉树都会遇到问题,除非:

  • 这是一个非常大(和/或退化)的二叉树;或
  • 结构不正确(例如结构中有一个循环);或
  • 您的时间限制非常小。

所以这些将是我要检查的第一件事

但是,就您而言,这可能是因为您需要更频繁地递归调用该函数。

通过在代码中对每个子树的深度函数调用两次(一次用于比较深度,一次用于返回最深的子树),您会大大增加工作量。最好缓存长度,以便您可以重复使用它们,例如(伪代码):

def maxDepth(nd):
    if nd == null:               # Empty-sub-tree depth is zero.
        return 0

    deepest = maxdepth(nd.left)  # Initially assume left is deepest.

    dright = maxdepth(nd.right)  # Or use right if deeper.
    if dright > deepest:
        deepest = dright

    return 1 + deepest           # Depth: this node plus deepest sub-tree.

【讨论】:

  • @wadda_wadda,这绝非巧合。如果您避开 Python 更深奥的部分,它是一种理想的教学和伪代码语言。美妙之处在于,您通常也可以使用真实系统实际测试您的伪代码 :-)
  • 感谢您的帮助!现在我知道我可以使用递归两次而不是每次四次。
猜你喜欢
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多