Why my solution does not work.


  • 1
    S

    /**

    • Definition for a binary tree node.

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

       if(root.left==null && root.right==null)
       return 1;
       
       else if(root.left==null)
       return maxDepth(root.right)+1;
       
       else if(root.right==null)
       return maxDepth(root.left)+1;
       else
       return (maxDepth(root.left)>maxDepth(root.right))?(maxDepth(root.left)+1):(maxDepth(root.right)+1);
      

      }
      }


  • 0
    S

    What if the root itself is null?

    Put the a condition
    if(root == null) return 0;


  • 0
    S

    there is the condition there in the code, while the dark part did not include it .


  • 0
    A

    Could u plz share the output for which it failed ?


Log in to reply
 

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