LeetCode 104. 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:

DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        return maxDepth(root, 0);
    }
    
    private int maxDepth(TreeNode root, int current) {
        if (root == null) return current;
        return Math.max(maxDepth(root.left, current + 1), maxDepth(root.right, current + 1));
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *