Question

link

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Stats

Frequency 1
Difficulty 1
Adjusted Difficulty 1
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

There are various ways to solve this question.

Eg. DFS, BFS, queue and so on.

Solution

I have nothing to say with the code.

Code

public int maxDepth(TreeNode root) {
    return helper(root, 0, 1);
}

private int helper(TreeNode node, int max, int level) {
    if (node == null) return max;
    if (node.left == null && node.right == null)
        return Math.max(max, level);
    max = helper(node.left, max, level + 1);
    max = helper(node.right, max, level + 1);
    return max;
}