二叉搜索树在C语言中的实现
我正在尝试用C实现一个二叉搜索树。我的插入方法工作不正常。此文件的打印顺序为: 12357610 预订单打印为: 532147106 邮购印刷品为: 1 4 2 3 6 10 7 5 我尝试过摆弄小于和大于,并使用左和右字符数组来标记下一步的每个输入,但到目前为止,我什么也并没有得到。我希望能得到一些帮助。多谢各位二叉搜索树在C语言中的实现,c,binary-search-tree,C,Binary Search Tree,我正在尝试用C实现一个二叉搜索树。我的插入方法工作不正常。此文件的打印顺序为: 12357610 预订单打印为: 532147106 邮购印刷品为: 1 4 2 3 6 10 7 5 我尝试过摆弄小于和大于,并使用左和右字符数组来标记下一步的每个输入,但到目前为止,我什么也并没有得到。我希望能得到一些帮助。多谢各位 int main(int argc, const char * argv[]) { struct node* root1 = (struct node*)m
int main(int argc, const char * argv[]) {
struct node* root1 = (struct node*)malloc(sizeof(struct node));
root1->value = 5;
root1->left = NULL;
root1->right = NULL;
root1->parent = NULL;
insert(3, root1);
insert(2, root1);
insert(1, root1);
insert(7, root1);
insert(10, root1);
insert(6, root1);
insert(4, root1);
}
//Does an initial comparison to set up the helper function 'H' to actually insert the value.
void insert(int val, struct node* rootNode) {
if (val < (rootNode)->value) {
insertH(val, rootNode, "left");
} else if (val > (rootNode)->value) {
insertH(val, rootNode, "right");
}
}
//Inserts val into the BST in its proper location
void insertH(int val, struct node* rootNode, char* helper) {
if (!strcmp(helper, "left")) {
if (rootNode->left == NULL) {
rootNode->left = (struct node*)malloc(sizeof(struct node));
rootNode->left->value = val;
(rootNode->left)->parent = rootNode;
rootNode->left->left = NULL;
rootNode->left->right = NULL;
} else {
if (val < (rootNode)->value) {
insertH(val, rootNode->left, "left");
} else if (val > (rootNode)->value) {
insertH(val, rootNode->left, "right");
}
}
} else if (!strcmp(helper, "right")) {
if (rootNode->right == NULL) {
rootNode->right = (struct node*)malloc(sizeof(struct node));
rootNode->right->value = val;
(rootNode->right)->parent = rootNode;
rootNode->right->left = NULL;
rootNode->right->right = NULL;
} else {
if (val < (rootNode)->value) {
insertH(val, rootNode->right, "left");
} else if (val > (rootNode)->value) {
insertH(val, rootNode->right, "right");
}
}
}
}
在BST中,新密钥总是插入到叶。我们从根开始搜索一个键,直到找到一个叶节点。找到叶节点后,新节点将作为叶节点的子节点添加。 这是一段带有注释的代码,您可以理解它是如何工作的,我希望这对您有所帮助
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
非常感谢。这些评论和你的解释让我明白了。我能够通过再次添加一个次要的助手类来保持父级能力。