implementation of binary trees code example
Example 1: binary tree in data structure
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;
while(1) {
parent = current;
if(data < parent->data) {
current = current->leftChild;
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
}
else {
current = current->rightChild;
if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}
Example 2: binary tree in c implementation
11 void insert(node ** tree, int val) {
12 node *temp = NULL;
13 if(!(*tree)) {
14 temp = (node *)malloc(sizeof(node));
15 temp->left = temp->right = NULL;
16 temp->data = val;
17 *tree = temp;
18 return;
19 }
20
21 if(val < (*tree)->data) {
22 insert(&(*tree)->left, val);
23 } else if(val > (*tree)->data) {
24 insert(&(*tree)->right, val);
25 }
26 }