gpt4 book ai didi

c - 如何在C中从右向左插入树中的节点?

转载 作者:行者123 更新时间:2023-11-30 16:51:17 25 4
gpt4 key购买 nike

现在,我知道下面的代码仅适用于根及其子级,但我不知道如何扩展它。每个节点在传递“孙子”之前都必须有子节点。谢谢。

void insert_node(IndexTree **root, Node *node) {
IndexTree *temp = (IndexTree*)malloc(sizeof(IndexTree));
memcpy(&temp->value.cs, node, sizeof(Node));
temp->left = NULL;
temp->right = NULL;
temp->tip=1;

if ((*root) == NULL) {
*root = temp;
(*root)->left = NULL;
(*root)->right = NULL;
}
else {
while (1) {
if ((*root)->right == NULL) {
(*root)->right = temp;
break;
}
else if ((*root)->left == NULL) {
(*root)->left = temp;
break;
}
}
}

最佳答案

使用递归函数。

树是递归数据类型( https://en.wikipedia.org/wiki/Recursive_data_type )。在它们中,每个节点都是它自己的树的根。尝试使用嵌套的 ifwhile 来处理它们只会限制树的深度。

考虑以下函数:void print_tree(IndexTree* root)。遍历树的所有值的实现执行以下操作:

void print_tree(IndexTree* root)
{
if (root == NULL) return; // do NOT try to display a non-existent tree

print_tree(root->right);
printf("%d\n", root->tip);
print_tree(root->left);
}

该函数调用自身,这是一个完全合法的举动,以确保您可以解析(几乎)任意深度的树。但是要注意无限递归!如果您的树有循环(因此不是树),或者如果您忘记包含退出条件,您将收到一个错误,称为...堆栈溢出!您的程序将有效地尝试在堆栈上添加无限函数调用,而您的操作系统几乎肯定不喜欢这样做。

对于插入,解决方案本身与打印树类似:

void insert_value(IndexTree* root, int v)
{
if (v > root->tip) {
if (root->right != NULL) {
insert_value(root->right, v);
} else {
// create node at root->right
}
} else {
// same as above except with root->left
}
}

关于c - 如何在C中从右向左插入树中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41836765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com