I want to create a binary tree which fills from left to right. i.e. if 1,2,3 are to be inserted then the tree should look like
1
/ \
2 3
I wrote an insert function, to insert the nodes in the tree. For the first node everything works okay..But, for the next node's (if I want to insert 4,5 as children to 2 and later 6,7 as children to 3) how should I switch between the parents (2,3)?
Here's my insert function
struct node * Insert(struct node * node, int data) {
if(node == NULL)
return (newNode(data));
else {
if(!node->left)
node->left = Insert(node->left,data);
if(!node->right)
node->right = Insert(node->right,data);
//can't figure out the condition when they both fail
}
}
complete binary tree. - user932887ncan be found at left:2n+1and right:2(n+1). It would make your insertion trivial, since all you're doing is tacking nodes on to the end of a sequence, resizing it as needed. Btw, this is commonly how binary heaps are maintained for, among other reasons, the simplicity of their indexing algorithms. Unrelated:struct node * nodean interesting, if not self-cryptic, choice of parameter names. - WhozCraig