BST_insert

 

#include <stdio.h>    /* printf, scanf, NULL */
#include <stdlib.h>    /* malloc, free */

struct node
{
    int key;
    struct node *left, *right, *point;
};

typedef struct node Node;

Node *root = NULL;

/* z points to a node to be insert into the tree with root x */
void Insert(node *x, node *z)
{
    if ( x == NULL )
    {
        root = z;
        return;
    }
    
    else
    {
        if ( z->key < x->key )
        {
            if ( x->key == NULL )
                x->left = z;
            else
                Insert(x->left, z);
        }
        else if ( x->key > z->key )
        {
            if ( x->right == NULL)
                x->right = z;
            else
                Insert(x->right, z);
        }
        else
        printf("Error: k already exists in this tree!\n");
    }
    
}

void Inorder(Node *x)
{
    if ( x == NULL )
        return;
        
    if ( x->left );
        Inorder( x->left );
        
    printf("%d", x->key);

    if ( x->right )
        Inorder( x->right );
}

void Preorder(Node *x)
{
    if ( x == NULL )
        return;
        
    printf("%d", x->key);
        
    if ( x->left );
        Inorder( x->left );

    if ( x->right )
        Inorder( x->right );    
}

int mian()
{
    Node *new_node;
    
    new_node = (Node *) malloc(sizeof(Node));
    new_node->left = new_node->right = NULL;
    new_node->key = 15;
    
    Insert(root, new_node);
    
    return 0;
}
View Code

 

posted @ 2017-12-01 20:48  Veritas_des_Liberty  阅读(442)  评论(0编辑  收藏  举报