|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importclasses.TreeNode; |
| 4 | + |
| 5 | +/**104. Maximum Depth of Binary Tree QuestionEditorial Solution My Submissions |
| 6 | +Total Accepted: 163413 |
| 7 | +Total Submissions: 333641 |
| 8 | +Difficulty: Easy |
| 9 | +Given a binary tree, find its maximum depth. |
| 10 | +
|
| 11 | +The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ |
| 12 | +publicclassMaximumDepthOfBinaryTree { |
| 13 | +/**Key to understand recursion, applies to generic recursion: |
| 14 | + * figure out all of the base cases/exit cases*/ |
| 15 | + |
| 16 | +//more verbose version |
| 17 | +publicintmaxDepth(TreeNoderoot) { |
| 18 | +if(root ==null)return0; |
| 19 | +intleftDepth =0; |
| 20 | +if(root.left !=null)leftDepth =maxDepth(root.left)+1; |
| 21 | +intrightDepth =0; |
| 22 | +if(root.right !=null)rightDepth =maxDepth(root.right)+1; |
| 23 | +returnMath.max(1,Math.max(leftDepth,rightDepth));//the reason we need to max with 1 here is actually |
| 24 | +//for this case: if(root != null), it's implicit here, because we checked root.left != null and root.right != null |
| 25 | +//then it comes to root != null |
| 26 | +//example test case for the above scenario: nums = {1,1,1} |
| 27 | + } |
| 28 | + |
| 29 | +//more concise version |
| 30 | +publicintmaxDepth_shorter_version(TreeNoderoot) { |
| 31 | +if(root ==null)return0; |
| 32 | +returnMath.max(maxDepth(root.left),maxDepth(root.right)) +1; |
| 33 | + } |
| 34 | + |
| 35 | +} |