题目:
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.
//给定一个二叉树,求其最小深度。最小深度是从根节点到最近的叶结点的最短路径上的结点数。
解题思路:
首先,给定的二叉树根节点如果为空,deep=0;
若不为空,则等于其左右结点为根节点的子树的最小深度的最小值加一(即为min(left.deep,right.deep)+1);
代码:
public class Solution {
public int run(TreeNode root) {
int deep;
if(root==null){
deep=0;
}else{
if(root.left==null&&root.right==null){
deep=1;
}
if(root.left==null&&root.right!=null){
deep=run(root.right)+1;
}else if(root.right==null&&root.left!=null){
deep=run(root.left)+1;
}else{
deep=Math.min(run(root.left)+1,run(root.right)+1);
}
}
return deep;
}
}
继续阅读与本文标签相同的文章
MJExtension中你可能不知道的一些点
-
重科技、重创新、重人才 常德高新区连续两年举办高新技术交流会
2026-05-18栏目: 教程
-
iRobot擦地机器人上新,更有意义的是机器人间互动的实现
2026-05-18栏目: 教程
-
科技的不断进步,分享缤越智能领航系统的使用方法
2026-05-18栏目: 教程
-
谷歌发布首款装有雷达的智能手机
2026-05-18栏目: 教程
-
Win10启用使用Sandbox
2026-05-18栏目: 教程
