[英]Deserialize a binary tree without 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
由于您的示例是广度优先算法的类型,因此可以通过队列解决(请参阅“ 广度优先”与“深度优先” )。 使用迭代深度优先方法也可以不排队(请参阅: https : //en.wikipedia.org/wiki/Iterative_deepening_depth-first_search )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.