我编写了一个使用递归反序列化二叉树的代码。有人可以帮助我调整它,以消除递归,因为我发现我不允许在我的任务中使用递归
#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
最佳答案
由于您的示例是广度优先算法的类型,因此可以使用队列来解决(请参阅 Breadth First Vs Depth First )。使用迭代深度优先方法也可以在没有队列的情况下进行(请参阅: https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search )。
关于c - 不使用递归反序列化二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48431894/