I'm working on a program in C++ that reconstructs a binary tree from file.
Besides what it is doing,my program should also be able to read hexadecimal numbers from file. Also the marker that indicates that the node has no child is -1 and i want it to be a character(for example #) but im not having much success with this.
Can someone help me with these two problems(reading hexadecimals from file and replacing -1 with # as a marker?).
#include <stdio.h>
#define MARKER -1
struct Node
{
int key;
struct Node* left, *right;
};
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
void deSerialize(Node *&root, FILE *fp)
{
int val;
if ( !fscanf(fp, "%d ", &val) || val == MARKER)
return;
root = newNode(val);
deSerialize(root->left, fp);
deSerialize(root->right, fp);
}
void preorder(Node *root)
{
if (root)
{
printf("%d ", root->key);
preorder(root->left);
preorder(root->right);
}
}
int main()
{
Node *root1 = NULL;
FILE *fp = fopen("tree.txt", "r");
deSerialize(root1, fp);
printf("preorder Traversal of the tree constructed from file:\n");
preorder(root1);
return 0;
}
As an example,if the file contains 1 2 4 -1 -1 5 -1 -1 3 -1 -1 it will display 1 2 4 5 3
Thank you!