题解 | #牛群的最短路径# 自顶向下遍历二叉树
牛群的最短路径
https://www.nowcoder.com/practice/c07472106bfe430b8e2f55125d817358
知识点
二叉树
思路
自顶向下遍历二叉树,维护长度,到叶子节点时更新答案,注意空节点长度为0。
时间复杂度
每个节点只会遍历一次,时间复杂度为
AC code (C++)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
int minDepth(TreeNode* root) {
if (!root) return 0;
int res = 2e9;
function<void(TreeNode*, int)> dfs = [&](TreeNode* root, int cnt) {
if (!root->left and !root->right) {
res = min(res, cnt + 1);
return;
}
if (root->left) dfs(root->left, cnt + 1);
if (root->right) dfs(root->right, cnt + 1);
};
dfs(root, 0);
return res;
}
};
