Sunday, August 2, 2009

Can anyone write c/c++ program for this binary tree problem??

There is a binary tree , a node having three pointers -- Left child, right child, parent. Now the problem is to delete the tree in top-down fashion ie First delete parent %26amp; then child.

Can anyone write c/c++ program for this binary tree problem??
how's this?:





typedef struct tree_struct


{


tree_struct *parent;


tree_struct *child_right;


tree_struct *child_left;


} tree_struct;





void main(void)


{


tree_struct *root;





// create the root using malloc(), add branches to the tree.


// Null pointers are assumed to indicate no child.





// now its time to free the tree in the manner you described (root-first)


free_tree(root);


}





void free_tree(tree_struct *tree)


{


tree_struct self;





self = *tree; // copy child pointers, note how parent is never used


free(tree);





if (self.child_right != NULL)


{


free_tree(self.child_right);


}


if (self.child_left != NULL)


{


free_tree(self.child_left);


}


}


No comments:

Post a Comment