0

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!

Mirel
  • 9
  • 1
  • 2
  • SO is *not* a *do-my-homework* service. I recommend compiling your code with all warnings and debug info (`g++ -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/)...) and [using the `gdb` debugger](https://sourceware.org/gdb/current/onlinedocs/gdb/) to understand the behavior of your program, then improve it (and repeat till satisfied) – Basile Starynkevitch Feb 11 '18 at 13:59
  • 1
    BTW, your code looks like C code (so compile it with `gcc`, not `g++`). Then your question should be tagged with `c`, not with `c++` since C and C++ are very different languages – Basile Starynkevitch Feb 11 '18 at 14:01
  • You could read an entire line (e.g. with [getline](https://stackoverflow.com/a/9171511/841108)...) then parse it (using `sscanf`, `strtok`, etc...) – Basile Starynkevitch Feb 11 '18 at 14:03

1 Answers1

2

Why don't use ifsteam instead of FILE?
And why don't use cout (#include <iostream>) instead of printf()?
See this for reading hexadecimal numbers(it's for ifstream, not for FILE).

And now about # instead of -1.
Just read first character as char, and check is it # or not.

J K
  • 632
  • 7
  • 24
  • Thank you for answers.I have resolved it..To answer your question,-1 can be a number from binary tree that's why i need a specific character – Mirel Feb 11 '18 at 14:22
  • @Mirel ok, do you need some code example of reading a number with checking if is it `#` or not? – J K Feb 11 '18 at 14:24