中序遍历,并将结点保存在数组中,数组k-1下标对应的结点就是二叉搜索树的第k个结点。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
void in_order(TreeNode* root, vector<TreeNode*>& result){
if(root==nullptr) return;
in_order(root->left,result);
result.push_back(root);
in_order(root->right,result);
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(pRoot==nullptr || k==0) return nullptr;
vector<TreeNode*> in_vec{};
in_order(pRoot, in_vec);
return in_vec[k-1];
}
};