给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点、
像dfs算法,算法结构也是比较重要的。还一点是其核心思路依赖于树结构,对树这种数据结构的操作和变量本质就是一种dfs,但是并非实解题中要用到树节点(更多只是用到dfs搜索结构)
同样,要多加练习的也是这种dfs搜索结构(代码框架基础是递归)。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
return minDfs(root, 1, 100000);
}
int minDfs(TreeNode root, int depth, int minDep){
if(root.left == null && root.right == null){
minDep = Math.min(depth, minDep);
return minDep;
}
if(root.left != null){
minDep = minDfs(root.left, depth + 1, minDep);
}
if(root.right != null){
minDep = minDfs(root.right, depth + 1, minDep);
}
return minDep;
}
}