作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
现在,我知道下面的代码仅适用于根及其子级,但我不知道如何扩展它。每个节点在传递“孙子”之前都必须有子节点。谢谢。
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 )。在它们中,每个节点都是它自己的树的根。尝试使用嵌套的 if
和 while
来处理它们只会限制树的深度。
考虑以下函数: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/
我是一名优秀的程序员,十分优秀!