【发布时间】:2012-12-17 23:23:05
【问题描述】:
一个非常愚蠢的问题,我几乎不好意思问。我一直在搜索过去 4 小时,测试了不同的算法,在纸上尝试了很多,但仍然无法使其正常工作。
我不会向您详细介绍项目实施的细节,但基本问题是:“您如何处理在预购二叉树中插入节点。
通过 Pre-Order BST,我的意思是所有节点都应该以这样一种方式插入,即使用 pre-order traversal 遍历树(例如用于打印)应该按升序打印节点。
我只需要一个简单的算法。我尝试了这里给出的简单插入算法(在stackoverflow上,但似乎不正确(也在纸上尝试过));。
节点基本上是这样的:
typedef struct testNode{
int key;
struct testNode *leftChild;
struct testNode *rightChild;
}NODE;
插入数据只是一个唯一整数列表。我创建一个以 int 为键的节点,然后应该将该节点添加到树中。我有根节点,它以 NULL 指针开始。
抱歉,如果有什么不清楚的地方。
感谢您的帮助!
编辑:根据下面提供的算法,这是我想出的:
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;
}
}
【问题讨论】:
-
我希望你刚刚粘贴了错误的结构。
-
当您说“预排序”二叉树时,您是指 BST(已经排序)还是与预排序遍历有关?
-
是的,这个结构是匆忙输入的,我会编辑它。预排序,从某种意义上说,我应该在树中插入节点,以便在使用预排序遍历遍历它时,它会以正确的顺序访问节点。
-
不会编译。节点不能包含自身的实例。 sizeof (struct testNode) 是什么?大小(结构测试节点)? 2* sizeof(testNode) + sizeof(int) ?
-
@wildplasser,你必须原谅我,我已经在这里待了将近 5 个小时。 leftChild 和 rightChild 实际上是指针。
标签: c binary-search-tree insertion preorder