您的位置:首页 > 其它

LeetCode(111) Minimum Depth of Binary Tree解题报告

2015-12-13 13:30 525 查看
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.

解题思路:

递归求解,如果有比min还小的深度,就更新min,需要注意的是,最小深度是叶子节点到根节点的深度。如果左子树或右子树为空,那么这个就不能计算在内。

public class Solution {
int min;
public int minDepth(TreeNode root) {
min = Integer.MAX_VALUE;
DepthOfTree(root,0);
return min;
}
public void DepthOfTree(TreeNode root,int depth){
if(root == null){
if(min > depth)
min = depth;
return ;
}
if(root.left == null)
DepthOfTree(root.right,depth+1);
else if(root.right == null)
DepthOfTree(root.left,depth+1);
else{
DepthOfTree(root.left,depth+1);
DepthOfTree(root.right,depth+1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: