Maximum Depth of Binary Tree

Problem

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.

Solution

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

Analysis

In every operation, we have choice to go to left node or go to right node to get the max depth
Therefore, we just use recursion to find the max result
If the node is null, we simply return 0
Otherwise, we just compare the current node's left and right, and get max of them with plus 1

results matching ""

    No results matching ""