Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

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.

DFS 相關的題目,使用遞迴會比較好做,

若是該節點為 null 回傳 0,若非 null 則繼續遞迴比較左右子樹的深度,將較深的深度 + 1 往上回傳

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