一个非常愚蠢的问题,我都快不好意思问了。我已经搜索了过去4个小时,测试了不同的算法,尝试了很多,但仍然无法使其工作。
我将跳过项目实现的详细信息,但基本问题是:“如何处理在先序二叉树中插入节点。”
通过 先序BST,我的意思是所有节点都应按这种方式插入,以便使用先序遍历(例如打印)遍历树时应按升序打印节点。
我只需要一个简单的算法。我尝试了在stackoverflow上提供的一个简单的插入算法(也在纸上尝试过),但似乎不正确;
节点基本上像:
插入数据只是一列唯一的整数。我创建一个以该整数作为键的节点,然后应将该节点添加到树中。我有根节点,它最初为空指针。
如果有不清楚的地方请谅解。
感谢您的帮助!
编辑:基于下面提供的算法,我得出了以下结果:
我将跳过项目实现的详细信息,但基本问题是:“如何处理在先序二叉树中插入节点。”
通过 先序BST,我的意思是所有节点都应按这种方式插入,以便使用先序遍历(例如打印)遍历树时应按升序打印节点。
我只需要一个简单的算法。我尝试了在stackoverflow上提供的一个简单的插入算法(也在纸上尝试过),但似乎不正确;
节点基本上像:
typedef struct testNode{
int key;
struct testNode *leftChild;
struct testNode *rightChild;
}NODE;
插入数据只是一列唯一的整数。我创建一个以该整数作为键的节点,然后应将该节点添加到树中。我有根节点,它最初为空指针。
如果有不清楚的地方请谅解。
感谢您的帮助!
编辑:基于下面提供的算法,我得出了以下结果:
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;
}
}