原题链接: https://leetcode.com/problems/minimum-depth-of-binary-tree/
1. 题目介绍
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],
return its minimum depth = 2.
2. 解题思路
本题和 104. Maximum Depth of Binary Tree 非常相似。一个是求树的最大深度,一个是求树的最小深度。方法都是一样的,那就是深度优先搜索+递归。
唯一不同之处在于,在求最小深度时,需要考虑只有左子树或者只有右子树的情况。比如测试样例 [1,2] , 1是根节点,2是左子树,没有右子树。这是返回的结果应该2,而不是1.
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
return helper(0,root);
}
public int helper(int depth,TreeNode root){
if(root == null){
return depth;
}
if(root.left == null && root.right == null){
return depth + 1;
}
int l = (root.left == null ? Integer.MAX_VALUE : helper(depth+1,root.left) );
int r = (root.right == null ? Integer.MAX_VALUE : helper(depth+1,root.right) );
return Math.min(l, r);
}
}