二叉搜索树的插入(ALDS1_8_A:Binary Search Tree I)

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

二叉搜索树的结点


Insert以根为起点寻找结点z在该插入的位置。设当前结点为x,如果z的键值小于x则将当前结点的左子结点作为下一个结点,反之则以右子节点作为下一个x,如此不断向叶节点搜索。在此过程中,程序将前一个结点保存在y里,用作z的候选父节点。当x抵达NIL时搜索结束,此时的y就是z的父节点了。

如果搜索结束时y仍为初始值NIL,就代表插入前的二叉树为空,z即成为根节点。如果插入前的二叉树不为空,那么插入的结点z将跟据键值成为y的左子节点或右子节点。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstdlib>

using namespace std;

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

node *root,*NIL;

void insert(int k)
{
    node *y=NIL;
    node *x=root;
    node *z;
    
    z=(node*)malloc(sizeof(node));
    z->key=k;
    z->left=NULL;
    z->right=NULL;
    
    while(x!=NULL){
        y=x;
        if(z->key<x->key){
            x=x->left;
        }else{
            x=x->right;
        }
    }
    
    z->parent=y;
    
    if(y==NIL){
        root=z;
    }else{
        if(z->key<y->key){
            y->left=z;
        }else{
            y->right=z;
        }
    }
}

void inorder(node *u)
{
    if(u==NULL){
        return ;
    }
    inorder(u->left);
    printf(" %d",u->key);
    inorder(u->right);
}

void preorder(node *u)
{
    if(u==NULL){
        return ;
    }
    printf(" %d",u->key);
    preorder(u->left);
    preorder(u->right);
}

int main()
{
    int n,k;
    string com;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        cin>>com;
        if(com=="insert"){
            scanf("%d",&k);
            insert(k);
        }else if(com=="print"){
            inorder(root);
            printf("\n");
            preorder(root);
            printf("\n");
        }
    }
    return 0;
}
/*
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值