问题描述:
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.
原问题链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/
问题分析
粗看起来,这个问题比较简单,因为要求的是二叉树的最短长度,那么只要找到它到叶节点的最近的距离就可以了。而这里可以很容易的得到一个递归的关系,就是minDepth(root) = Math.min(minDepth(root.left), minDepth(root.right)) + 1;
于是我们可以得到如下的代码:
/**
* 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 minDepth(TreeNode root) {
if(root == null) return 0;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
在实际运行的时候却提示结果错误了。这里还有一个额外的要求,就是因为要找一个到叶节点的最近距离。在一些特殊的情况下,比如根节点的某个子树为空或者两个子树都是空,那么我们要啊返回的结果就不一样。我们必须要尽量找到那个有叶子节点的一边,而不是纯找最短的路径。把这两个条件考虑在内之后。
于是我们可以得到如下的代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int a = minDepth(root.left);
int b = minDepth(root.right);
if(a + b == 0) return 1;
if(a * b == 0) return a + b + 1;
return Math.min(a, b) + 1;
}
}