您的位置:首页 > 其它

LeetCode 41 Minimum Depth of Binary Tree

2014-08-30 18:27 369 查看
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 nearest leaf node.

分析:

二叉树用递归。

/**
* 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 lMin = minDepth(root.left);
int rMin = minDepth(root.right);
if(lMin==0 && rMin==0) return 1;
//下面这两行是避免把只有一个孩子的中间节点当成叶子节点
if(lMin == 0) lMin = Integer.MAX_VALUE;
if(rMin == 0) rMin = Integer.MAX_VALUE;
return Math.min(lMin, rMin) + 1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 递归 LeetCode