首页 > 其他 > 详细

BST_insert

时间:2017-12-01 21:39:56      阅读:341      评论:0      收藏:0      [点我收藏+]

 

技术分享图片
#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

 

BST_insert

原文:http://www.cnblogs.com/ruruozhenhao/p/7944387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!