一个令人痛苦的愚蠢的问题,我几乎羞于启齿地问。我在过去的4个小时里一直在搜索,测试了不同的算法,在纸上尝试了相当多的时间,仍然不能让它工作。
我将省去项目实现的细节,但基本的问题是:“如何处理在预排序二叉树中插入节点。
通过预排序BST,我的意思是所有节点都应该以这样的方式插入,即使用预排序遍历树(例如打印)应该以升序打印节点。
我只需要一个简单的算法。我尝试了这里给出的一个简单的插入算法(在stackoverflow上,但它似乎不正确(也在纸上尝试过));。
这些节点基本上类似于:
typedef struct testNode{
int key;
struct testNode *leftChild;
struct testNode *rightChild;
}NODE;插入数据只是一个唯一整数的列表。我创建了一个以int为键的节点,然后应该将该节点添加到树中。我有根节点,它从一个空指针开始。
如果有什么不清楚的地方,很抱歉。
谢谢你的帮助!
编辑:基于下面提供的算法,这是我想出来的:
void insert(NODE **tree,int key){
if(*tree){
if ((*tree)->key >= key){
//Insert before this .....
NODE *temp = createNode(key);
temp->lc = (*tree);
(*tree) = temp;
}
else if(!(*tree)->rc){
//Right Child doesn't exist ....
insert(&(*tree)->lc,key);
}
else if((*tree)->rc->key < key){
//Right child exists and is smaller than spread ... insert left ...
insert(&(*tree)->lc,key);
}
else{
//Right child exists and is greater than spread ... insert right ...
insert(&(*tree)->rc,key);
}
//If the code as progressed to this point, insertion must have occured,
//and the code returns ......
} else {
//the **tree pointer points to NULL. Insert here ....
SPREADNODE *temp = createSpreadNode(spread);
//temp->lc = (*tree);
(*tree) = temp;
}
}发布于 2012-12-18 07:42:46
考虑一下预排序BST的定义:根节点是最小的元素,它的两个子节点或者也是预排序树,使得右子树的根大于左子树中的任何值。
因此,一种可行的算法是:
这不太可能产生一个非常平衡的树,但它应该可以工作。我至少还能想到一个简单的替代方案,毫无疑问,有一些方法可以让我留给读者的练习变得更加平衡;-)
https://stackoverflow.com/questions/13923948
复制相似问题