Why my program runs out with, Time Limit Exceeded HELP!


  • 0
    S

    /**

    • Definition for binary tree

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public int maxDepth(TreeNode root) {
      if(root == null){
      return 0;
      }

       return maxDepth(root.left)>maxDepth(root.right) ?1+ maxDepth(root.left) :1+ maxDepth(root.right);
      

      }
      }


  • 5
    S

    Did you notice that for every 'root', your code calls maxDepth() on both of its children TWICE? When you get the depth of subtrees, you should save these results, rather than computing them all over again.


  • 0
    M

    yes, just like this:

    
    tempLeft = maxDepth(root -> left);  
    tempRight = maxDepth(root -> right);   
    return tempLeft > tempRight ? tempLeft + 1 : tempRight + 1;   
    

  • 0
    S

    thank you very much!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.