题解 | #二叉搜索树的第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 <iterator>
#include <queue>
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
int KthNode(TreeNode* proot, int k) {
// write code here
if(proot==nullptr)
{
return -1;
}
queue<TreeNode*>que;
que.push(proot); //把树的头节点塞入队列
vector<int>res;
while(!que.empty())
{
TreeNode* temp = que.front();
int z = que.front()->val;
que.pop();
res.push_back(z);
if(temp->left)
{
que.push(temp->left);
}
if(temp->right)
{
que.push(temp->right);
}
}
sort(res.begin(),res.end());
if(k>res.size()||k==0)
{
return -1;
}
return res[k-1];
}
};
查看9道真题和解析