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);
}
}
返回超出时间限制。我想知道为什么会这样,我的代码出了什么问题?
答案 0 :(得分:0)
你真的很亲近。我认为你的目标是:
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(对于根)。
答案 1 :(得分:0)
很难想象你会遇到大多数二叉树的问题,除非:
所以那些将是我要检查的第一个。
但是,在您的情况下,可能是因为您需要更频繁地递归调用函数。
通过在代码中为每个子树调用深度函数(一个用于比较深度,一个用于返回最深的子树),可以大大增加工作量。最好缓存长度,以便可以重复使用它们,例如(伪代码):
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.