繁体   English   中英

二叉树的最大深度

[英]Maximum Depth of Binary Tree

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);
    }
}

它返回超过时间限制。 我不知道为什么会这样,我的代码出了什么问题?

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

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中的较大者(对于根)。

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

  • 这是一个很大的(和/或退化的)二叉树; 要么
  • 它的结构不正确(例如,结构中有一个圆环); 要么
  • 您的时间限制很小。

因此,这些将是我首先要检查的事情。

但是,在您的情况下,可能是因为您需要多次递归地调用该函数。

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

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.

暂无
暂无

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

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