题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <algorithm> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param proot TreeNode类 * @param k int整型 * @return int整型 */ vector<int> v; void visit(TreeNode* root) // 前序遍历存储val { if(!root) return; v.push_back(root->val); visit(root->left); visit(root->right); } int KthNode(TreeNode* proot, int k) { // write code here TreeNode* root = proot; if(!root) return -1; visit(root); sort(v.begin(), v.end()); // 默认升序 if(k > v.size()) return -1; for(int i = 0; i < v.size(); ++i) { if(i == k-1) { return v[i]; } } return -1; } };
挤挤刷刷! 文章被收录于专栏
记录coding过程