Insert Node
#include <stdio.h>
#include <stdlib.h>
 
typedef struct Tnode {
    int data;
    struct Tnode *left, *right;
} Tnode;
 
// Insert
 
void insert(Tnode **root, int value)      // root is a pointer points to a Tnode pointer, so we can modify the Tnode pointer 
{
    if (*root == NULL) {
        *root = (Tnode*)malloc(sizeof(Tnode));  // we can assign a new Tnode pointer to *root
        (*root)->data = value;
        (*root)->left = (*root)->right = NULL;
    }
    else {
        if (value <= (*root)->data) 
            insert(&(*root)->left, value);
        else 
            insert(&(*root)->right, value);
    }
}
 
Tnode* insert2(Tnode *root, int item)          // root is a pointer, not pointer to pointer
{
    if (root == NULL) {
        Tnode *new = (Tnode*)malloc(sizeof(Tnode));
        new->data = item;
        new->left = new->right = NULL;
        return new;
    }
    else {
        if (root->data >= item)
            root->left = insert2(root->left, item);
        else
            root->right = insert2(root->right, item);
        return root;
    }
}
 
int main()
{
    int data;
    Tnode *T = NULL;        // must initialize its value before passing to insert(), or segmentation fault could happen
    while (scanf("%d", &data)) {
        insert(&T, data);
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License