题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
使用栈遍历树, 当遍历到右子树时, 已经是从最小的开始了
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(pRoot==nullptr||k==0)
return nullptr;
stack<TreeNode*> stack;
int count = 0;
TreeNode* node = pRoot;
do{
if(node!=nullptr){
stack.push(node);
node = node->left;
}else{
node = stack.top();
stack.pop();
count++;
if(count==k)
return node;
node = node->right;
}
}while(node!=nullptr||!stack.empty());
return nullptr;
}
};
中序遍历, 比较简陋
class Solution {
public:
vector<TreeNode *> vt;
void inOrder(TreeNode *pRoot) {
if (nullptr == pRoot)
return;
inOrder(pRoot->left);
vt.push_back(pRoot);
inOrder(pRoot->right);
}
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if ((nullptr == pRoot) || (k < 1))
return nullptr;
inOrder(pRoot);
if (k > vt.size())
return nullptr;
TreeNode * ret = nullptr;
for (int i = 0; i < k; i++) {
ret = vt[i];
}
return ret;
}
};
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};