您的位置:首页 > 其它

Leetcode: Minimum Depth of Binary Tree 理解分析

2014-04-16 15:27 337 查看
题目大意:给定一个二叉树,找出树的最小深度。

理解:此题与Maximum Depth of Binary Tree(http://blog.csdn.net/zhao_shanshan/article/details/23381923)相对,让你找出最小的深度,即从根节点到叶子节点的一条节点数最少的路径。

采用递归遍历,用一个全局变量count记录扫描过节点的个数,即树的深度,用一个全局变量min记录此时扫描过的最小的深度。扫描的过程中,增加剪枝:如果还未扫描的叶子节点,此时的count已经大于min,则这条路径没必要再继续走,直接返回最小值min。

实现:

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int min = Integer.MAX_VALUE;
private int count = 0;
public int minDepth(TreeNode root) {
if(root == null)    return 0;
count ++;
if(count > min) return min;
if(root.left == null && root.right == null) {
return count;
}
if(root.left != null) {
int res = minDepth(root.left);
if(res < min)   min = res;
count --;
}
if(root.right != null) {
int re = minDepth(root.right);
if(re < min)    min = re;
count --;
}
return min;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息