【问题标题】:How to insert nodes in tree in C from right to left?如何从右到左在C中的树中插入节点?
【发布时间】:2017-01-24 18:52:19
【问题描述】:

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

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;
        }
    }
}

【问题讨论】:

  • 因为你只是将节点按固定顺序放置,所以这实际上是一个数组,而不是一棵树。

标签: c tree insert nodes


【解决方案1】:

使用递归函数。

树是递归数据类型 (https://en.wikipedia.org/wiki/Recursive_data_type)。在它们中,每个节点都是它自己树的根。尝试使用嵌套的 ifs 和 whiles 与它们一起工作只会限制您在树的深度上。

考虑以下函数: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
    }
}

【讨论】:

  • 作为一个简短的说明,我假设您在这里使用二叉搜索树,因此if (v > root->tip) 条件。
  • 大错特错。没有比较功能。任务是在开始下一个级别之前填充每个级别。递归解决方案无法确定下降的一侧。最好的策略是只计算节点总数,然后在最后添加下一个。
【解决方案2】:

使用链接表示创建完整二叉树可能是一个有趣的编程问题。这里链接表示非数组表示,其中左右指针(或引用)分别用于引用左右子节点。如何编写一个始终在最后一级和最左侧可用位置添加新节点的插入函数? 要创建链接的完全二叉树,我们需要以级别顺序方式跟踪节点,以便下一个要插入的节点位于最左边的位置。队列数据结构可用于跟踪插入的节点。
以下是在完整二叉树中插入新节点的步骤。 (右歪)
1. If the tree is empty, initialize the root with new node.

2. Else, get the front node of the queue.

……. if the right child of this front node doesn’t exist, set the right child as the new node. //as per your case
…….else If the left child of this front node doesn’t exist, set the left child as the new node.

3. If the front node has both the left child and right child, Dequeue() it.

4. Enqueue() the new node.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多