简体   繁体   中英

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

It returns Time Limit Exceeded. I wonder know why this happens, what's wrong with my code?

You're really close. I think you were aiming for this:

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

I would assume the reason you're exceeding a time limit is because you have -way- more recursive calls than you need to have. In order to solve this problem, you just have to calculate the size of the left sub-tree, the size of the right sub-tree, and return the larger of the two values + 1 (for the root).

It's hard to envisage you'll strike a problem with most binary trees unless:

  • it's a really big (and/or degenerate) binary tree; or
  • it's not structured correctly (such as having a circular loop in the structure); or
  • your time limit is very small.

So those would be the first things I would check.

However, in your case, it's possibly because you're calling the function recursively far more often that you need to.

By having two calls to the the depth function in your code for each sub-tree (one for comparing the depths and one for returning the deepest sub-tree), you greatly increase the workload. It would be better to cache the lengths so you could re-use them, something like (pseudo-code):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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