【发布时间】:2020-04-01 20:29:37
【问题描述】:
我想获得一个叶节点作为输出(只是其中一个)。但每次都不是同一个叶节点...我想在“srand”的帮助下每次都获得一个不同的叶节点函数...我尝试使用数组来解决此问题,但未能成功。然后我决定在评论这篇文章的朋友的帮助下继续使用不同的算法...
如果左边的孩子很奇怪,我会生成一个随机整数,反之亦然......
但是得到与输出相同的节点并不能解决问题...
void LeafNodesRandomly(BST*p)
{
int i;
srand(time(NULL));
i=rand()%2;//Generating a random int for determining to go right or left of a current node
//printf("%d\t",i);
while(p->left !=NULL || p->right !=NULL)
{
if(p->left==NULL && p->right!=NULL)//Just have a right child
{
p=p->right;
if(p->left==NULL && p->right==NULL)//If the right child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
if(p->left!=NULL && p->right==NULL)//Just have a left child
{
p=p->left;
if(p->left==NULL && p->right==NULL)//If the left child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
if(p->left!=NULL && p->right!=NULL)// The current node have two children
{
if(i==0)
{
p=p->left;
if(p->left==NULL && p->right==NULL)// If the randomly generated int is "0" go left child and if the left child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
if(i==1)
{
p=p->right;
if(p->left==NULL && p->right==NULL)// If the randomly generated int is "1" go right child and if the right child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
}
/*if(i==0) // If you open this if and else block you can randomly reach some of other leafs!!!
{
i=i+1;
}
else
i=i-1;
} */
}
}
这是我的主要功能:
我有 13 或 NULL 作为输出
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include "bst.h"
int main()
{
BST*root=NULL;
root=AddNode(root,9);
root=AddNode(root,11);
root=AddNode(root,7);
root=AddNode(root,13);
root=AddNode(root,10);
root=AddNode(root,5);
root=AddNode(root,6);
root=AddNode(root,8);
LeafNodesRandomly(root);
}
【问题讨论】:
-
当你说“随机”时,你的意思是用统一的概率选择任何特定的叶子吗?或者是否可以使用受树平衡方式影响的非均匀概率进行选择?
-
一种方法是向每个节点添加一个字段,该字段计算当前节点下方的节点数,并在每次插入/删除树时更新它。然后选择一个随机元素,从根开始,以与每侧节点数成正比的概率下降左或右分支。
-
@YTE1008 抱歉,但这并不能真正回答我提出的问题。
-
所以你的意思不是“随机”而是“任意”?然后总是沿着左边的树枝走,直到你碰到一片叶子。
-
'我尝试过,但无法成功使用此解决方案"。然后展示该尝试,以便我们帮助指出它的问题所在。
标签: c data-structures binary-tree binary-search-tree