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;
}