您的位置:首页 > 其它

minimum-depth-of-binary-tree

2016-06-14 09:56 225 查看
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.

题目的意思是找出根节点到叶子节点最短的一条路径的深度,这个深度等于左子树与右子树中最小的深度+1,但需要考虑的是如果左子树或者右子树为空,那么这个深度就是不为空的子树深度+1。public class Solution {
public int run(TreeNode root) {
if(root==null) return 0;
else{
if(root.left==null&&root.right==null) return 1;//到达叶子节点

else{
int left_num=run(root.left)+1;
int right_num=run(root.right)+1;

if(left_num>right_num){
if(root.left==null||root.right==null) return left_num;
else return right_num;
}else{
if(root.left==null||root.right==null) return right_num;
else return left_num;
}
}
}
}
}
2.还有一个类型的题目,求二叉树从根节点到某个叶子节点路径的val值最小是多少。做法与上面一样。
private static int getlength(TreeNode tNode) {
if(tNode==null) return 0;
else{
int minLeft=getlength(tNode.leftNode)+tNode.value;
int minRight=getlength(tNode.rightNode)+tNode.value;
if(tNode.leftNode==null) return minRight;
if(tNode.rightNode==null) return minLeft;
if(minLeft<minRight) return minLeft;
else return minRight;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: