解法一 | #二叉搜索树的第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 <cstddef>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
void inorder(TreeNode* root,vector<int>& res){
if(!root){
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
int KthNode(TreeNode* proot, int k) {
// write code here
// 二叉树的中序遍历
vector<int> res;
inorder(proot, res);
if(proot == NULL || res.size()<k || k == 0){
return -1;
}
return res[k-1];
}
};
对二叉搜索树进行中序遍历,将节点值存储到res中,返回res[k-1]即可。
