LeetCode 75
Maximum Depth of Binary Tree
- Problem
- LC 104
- Topic
- Tree DFS
- File
- official75_LC104MaximumDepthOfBinaryTree.java
- Path
- pkg5leetcode/official75/official75_LC104MaximumDepthOfBinaryTree.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC104MaximumDepthOfBinaryTree.java
- Approach
- Recursive 1 + max(left, right) depth.
- Complexity
- Time O(n), Space O(h)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Maximum Depth of Binary Tree | LC 1045 * APPROACH: Recursive 1 + max(left, right) depth.6 * COMPLEXITY: Time O(n), Space O(h)7 */8public class official75_LC104MaximumDepthOfBinaryTree {9 /** Same shape as pkg5leetcode/common/TreeNode.java (nested for single-file runs). */10 11 static class TreeNode {12 int val;13 TreeNode left, right;14 TreeNode(int val) { this.val = val; }15 }16 17 static int maxDepth(TreeNode root) {18 if (root == null) return 0;19 return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));20 }21 22 public static void main(String[] args) {23 TreeNode root = new TreeNode(3);24 root.left = new TreeNode(9);25 root.right = new TreeNode(20);26 root.right.left = new TreeNode(15);27 root.right.right = new TreeNode(7);28 check(maxDepth(root) == 3, "case1");29 check(maxDepth(null) == 0, "case2");30 System.out.println("all tests passed");31 }32 33 static void check(boolean cond, String name) {34 if (!cond) throw new AssertionError("FAILED: " + name);35 System.out.println(" PASS " + name);36 }37}