Blind 75

Maximum Depth of Binary Tree

Problem
LC 104
Category
Tree
File
blind75_LC104MaximumDepthOfBinaryTree.java
Path
pkg5leetcode/blind75/blind75_LC104MaximumDepthOfBinaryTree.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC104MaximumDepthOfBinaryTree.java
Approach
Recursive 1 + max(left, right) depth.
Complexity
Time O(n), Space O(h)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC104MaximumDepthOfBinaryTree.java
1package pkg5leetcode.blind75;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 blind75_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}