二叉搜索树的第k个节点
二叉搜索树的第k个结点
http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
queue<TreeNode*> q;
TreeNode* cur = nullptr;
if(root->left)
func(root->left);
if(cur == nullptr)
{
q.push(root);
}
if(root->right)
func(root->right);
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(pRoot == nullptr)
return nullptr;
return nullptr;
while(k>1)
{
q.pop();
--k;
}
return q.front();
}
};
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
//进行中序遍历,并将元素保留到队列中
void func(TreeNode* root)
{TreeNode* cur = nullptr;
if(root->left)
func(root->left);
if(cur == nullptr)
{
q.push(root);
}
if(root->right)
func(root->right);
}
TreeNode* KthNode(TreeNode* pRoot, int k) {
if(pRoot == nullptr)
return nullptr;
func(pRoot);
//进行判断k在不在队列q的大小范围内,如果不在,则返回空
if(k == 0 || k > q.size())return nullptr;
while(k>1)
{
q.pop();
--k;
}
return q.front();
}
};