我遇到了在 BST 中找到第K 个最小元素的问题。
我写的函数是:
//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的值没有增加。当控制语句在交叉计数递增操作后到达时,为什么它无法递增值?编译器是 g++ 5.4
您的代码中有一个似乎是无意的错误。设置indicator
为0以外的某个值:
if(indicator==0)
{
//indicator=0; // MISTAKE
indicator=1 //OR SOME VALUE OTHER THAN 0
.
.
.
}
之后count
将按预期工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句