题解 | #二叉树之寻找第k大#
二叉树之寻找第k大
https://www.nowcoder.com/practice/8e5f73fa3f1a407eb7d0b0d7a105805e
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param k int整型
* @return int整型
*/
void dfs(TreeNode* root, vector<int>& v)
{
if(!root)
return;
dfs(root->left, v);
v.emplace_back(root->val);
dfs(root->right, v);
}
int kthLargest(TreeNode* root, int k) {
// write code here
vector<int> v;
dfs(root, v);
return v[v.size()-k];
}
};
虚数五行区解题中心 文章被收录于专栏
非淡泊无以明志,非宁静无以致远