Day13 2023/03/13
难度:简单
题目
30、给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。例如:
输入:1 2 3 4 5 # 6 # # 7 # # # (层序遍历的方式创建链表) 输出:最小深度为:3
本题求得是最小深度,之前这篇博客里求的得是最大深度,并且是完全基于深度优先算法来实现得。但是本题求最小深度,并不是 在求最大深度代码的基础上,简单的修改一下返回值,让每次递归返回最小值就可以得(千万注意这里❌),如果完全居于深度优先算法实现求最小深度,可能会出现 "路径选择错误得问题"
static int minTreeHigh(Tree root){
if (root == null)return 0;
int Ldepth = minTreeHigh(root.left);
int rdepth = minTreeHigh(root.right);
if (root.left == null && root.right != null)Ldepth = rdepth;
if (root.right == null && root.left != null)rdepth = Ldepth;
return Ldepth < rdepth ? Ldepth + 1 : rdepth + 1;
}