104. Maximum Depth of Binary Tree (divide & conquer)

time: O(n), visit each node exactly once

space: O(n), call stack worst case is n (depth n)

compare to no. 111

this is postorder

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int left = maxDepth(root.right);
        int right = maxDepth(root.left);

        return Math.max(left, right) + 1;
    }
}

or like this

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

Last updated