【发布时间】:2019-10-23 02:07:15
【问题描述】:
我遇到了一个问题,要在 BST 中找到 Kth 个最小的元素。
我写的函数是:
//THE FUNCTION TAKES ROOT OF TREE AND THE VALUE OF K AS INPUT
int KthSmallestElement(Node *root, int k)
{
static int indicator=0;
static Node* temp_root=NULL;
static int count=0; //PROBLEM
int i=0;
if(indicator==0)
{
indicator=0;
temp_root=root;
}
if(root)
{
i=KthSmallestElement(root->left,k);
if(i!=0)
{
indicator=0;
temp_root=NULL;
count=0;
return i;
}
++count;
printf("count %d k %d\n",count,k);
printf("root.data %d\n\n",root->data);
if(count==k)
{
return root->data;
}
i=KthSmallestElement(root->right,k);
if(i!=0)
{
indicator=0;
count=0;
temp_root=NULL;
return i;
}
}
if(temp_root==root)
{
indicator=0;
count=0;
temp_root=NULL;
}
return 0;
}
我必须给出的输入类型是:
输入:
1 //NO OF TEST CASES
11 //NO OF NODES IN THE BST
962 29 643 291 8 298 133 481 175 916 948 //VALUE OF NODES IN BST
6 //VALUE OF K
输出:
count 1 k 6
root.data 8
count 1 k 6
root.data 29
count 1 k 6
root.data 133
count 1 k 6
root.data 175
依此类推,以升序打印所有剩余值。现在我真的很困惑为什么 count 的值没有增加。由于控制语句在通过 count 递增操作后到达,那么为什么它无法递增值?编译器是g++ 5.4
【问题讨论】:
-
你在几个地方有
count=0。那些会被击中吗?
标签: c++ recursion static g++ binary-search-tree