题解 | #二叉树之寻找第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 <utility> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param k int整型 * @return int整型 */ /* 思路:中序遍历,使用一个vector容器来保存其中的遍历结果,然后直接使用下标进行访问。 */ vector<int> res; // int count = 0; void getorder(TreeNode* root){ if(root != nullptr){ getorder(root->left); res.push_back(root->val); getorder(root->right); } } int kthLargest(TreeNode* root, int k) { // write code here getorder(root); int n = res.size(); return res[n-k]; } };