题解 | #牛群仰视图# DFS
牛群仰视图
https://www.nowcoder.com/practice/0f37a18320c4466abf3a65819592e8be
知识点
DFS 遍历二叉树
思路
这道题题面很迷惑,看样例是找到从左到右的叶子结点。
先序遍历二叉树,找到叶子结点则加入答案。只要先遍历左子树,再遍历右子树,就能从左到右得到答案。
时间复杂度
遍历一遍二叉树,时间复杂度为
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整型vector
*/
vector<int> bottomView(TreeNode* root) {
// 找到所有的叶子结点
vector<int> res;
function<void(TreeNode*)> dfs = [&](TreeNode* root) {
if (!root) return;
if (!root->left and !root->right) {
res.push_back(root->val);
return;
}
dfs(root->left);
dfs(root->right);
};
dfs(root);
return res;
}
};
