I wrote a code for Deserialization of a binary tree using recursion.Can someone help me tweak it in a way that i can eliminate recursion because i have found that i am not allowed to use recursion in my task
#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;
}
Here is an example: If i read 1 2 3 4 0 0 0 0 5 0 7 0 0 it will display a binary tree traversed in preorder like this
1
2 5
3 4 7