0

I'm trying to build a binary tree with a file and I'm having trouble setting the parent for each tree node. I know I need to store the previous tree node, but I don't know how to do it.

I've tried using a static int variable called count to determine if the parent for a tree node is the previous tree node's left subtree or the previous tree node's right subtree. However, I realized that I'm essentially assigning nothing to the parent.

typedef struct Treenode
{
    int data;
    struct Treenode *left, *right, *parent;
} TreeNode, *TreeNodePtr;

static int count = 0;

TreeNodePtr buildTree(FILE * in)
{
    int num;
    fscanf(in, "%d", &num);

    if (num == 0)
        return NULL;

    TreeNodePtr p = (TreeNodePtr) malloc(sizeof(TreeNode));
    TreeNodePtr prev = (TreeNodePtr) malloc(sizeof(TreeNode));


    if (count == 0)
        p->parent = NULL;
    else if (count == 1)
        p->parent = prev->left;
    else if (count == 2)
        p->parent = prev->right;

    p->data = num;

    count = 1; 
    prev->left = p->left = buildTree(in);
    count = 2;
    prev->right = p->right = buildTree(in);
    return p;
}
Dante
  • 13
  • 4
  • 1
    [Casting malloc is bad](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) - Please read – Ed Heal Oct 08 '19 at 05:42
  • What is `TreeNodePtr`? – Jabberwocky Oct 08 '19 at 05:42
  • 4
    That's a very unusual way to try building a tree. What happens if there are a few million records in the file? You're going to recurse far too deeply. You should be using iterative code for this. – Jonathan Leffler Oct 08 '19 at 05:43
  • 2
    Also hiding pointers is also bad – Ed Heal Oct 08 '19 at 05:43
  • `prev` should point to an existing node or be `NULL`, so you don't need to allocate anything for that. Allocation with `malloc` "creates" a new node, so you need to allocate memory for `p`, but not for `prev`. – M Oehm Oct 08 '19 at 05:44
  • 4
    See [Is it a good idea to typedef pointers?](https://stackoverflow.com/questions/750178/) — tl;dr the answer is usually "No", with an exception for function pointers. – Jonathan Leffler Oct 08 '19 at 05:44

0 Answers0