跳转至

111. Minimum Depth of Binary Tree

Leetcode Tree Depth-first Search Breadth-first Search

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 2.

分析

DFS版本的递归:

public int minDepth(TreeNode root) {
    if(root == null) return 0;
    int left = minDepth(root.left);
    int right = minDepth(root.right);
    return (left == 0 || right == 0) ? left + right + 1: Math.min(left, right) + 1;
}

最关键在于判断左子树和右子树存在的情况,并区别对待。

类似题目: Q104. Maximum Depth of Binary Tree