剑指OFFER 二叉搜索树的第k个结点
剑指OFFER 二叉搜索树的第k个结点
分析
先中序遍历一遍,保存下结果,然后取第k小个结点即可
代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<TreeNode* > v;
void recur(TreeNode* node)
{
if(node == NULL)return;
recur(node->left);
v.push_back(node);
recur(node->right);
}
TreeNode* KthNode(TreeNode* root, int k)
{
if(root==NULL || k<=0)return NULL;
recur(root);
if(k>=v.size()+1)return NULL;
return v[k-1];
}
};