【问题标题】:Deserialize a binary tree without recursion无递归反序列化二叉树
【发布时间】:2018-01-24 21:28:52
【问题描述】:

我编写了一个使用递归反序列化二叉树的代码。有人可以帮我调整它以消除递归,因为我发现我不允许在我的任务中使用递归

#include <stdio.h>
#define NO_CHILD 0
//node
struct Node
{
    int key;
    struct Node* left, *right;
};
//create a node
Node* _NewNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
//extract binary tree from text
void _ReadBinaryTree(Node *&root, FILE *file)
{
    //read element;if there are no more elements or the elemnt has NO_CHILD stop
    int value;
    if ( !fscanf(file, "%d ", &value) || value == NO_CHILD)
       return;
    //otherwise create the node and recursion for its children
    root = _NewNode(value);
    _ReadBinaryTree(root->left, file);
    _ReadBinaryTree(root->right, file);
}

//preorder traversal
void _Preorder(Node *root)
{
    if (root)
    {
        printf("%d ", root->key);
        _Preorder(root->left);
        _Preorder(root->right);
    }
}
int main()
{
    FILE *file;
    Node *root1 = NULL;
    file = fopen("tree.txt", "r");
    _ReadBinaryTree(root1, file);
    printf("Preorder traversal:\n");
    _Preorder(root1);
    return 0;
}

这是一个例子: 如果我读到 1 2 3 4 0 0 0 0 5 0 7 0 0 它将显示一个像这样按顺序遍历的二叉树

            1
    2           5
3       4           7

【问题讨论】:

  • 无递归构建二叉树?这个练习的作者有一个扭曲的想法......
  • 使用栈数据结构
  • 顺便说一句,据我所知,单个前序遍历序列不足以重建树。
  • @Ron,但是,但是,有新的关键字 :-)
  • 要在没有递归的情况下执行此操作,您需要一个数据结构来保存指向当前节点路径上的节点的指针。实现细节并不重要,但它基本上可以用作堆栈。如果你的 Node 结构有一个父指针,那么树本身就可以达到这个目的,但我假设你不允许进行这种修改。

标签: c tree binary-tree binary-search-tree


【解决方案1】:

由于您的示例是广度优先算法的类型,因此可以使用队列解决(查看Breadth First Vs Depth First)。使用迭代深度优先方法也可以不使用队列(查看:https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search)。

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 2020-04-09
    • 2021-11-14
    • 1970-01-01
    • 2016-04-19
    • 2014-03-29
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多