在不递归的情况下反序列化二叉树

时间:2018-01-24 21:28:53

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

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

#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

1 个答案:

答案 0 :(得分:1)

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