二叉搜索树的根节点插入

本文介绍了一种特殊的二叉搜索树插入方法,新节点不仅可以在底层插入,还可以通过旋转操作达到树的较高层级甚至成为根节点。文章提供了具体的 C 语言实现代码,包括右旋、左旋和插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在标准二叉搜索树中,每个新节点都会插入到树的底层的某个地方,替换某个外部节点。这种状态并不是一个绝对的要求;也可以从根节点插入,方法是先插入到相应外部节点然后在通过旋转,转到根节点,下面给出实现:

#include <stdio.h>
#include <stdlib.h>


struct Tree
{
int item;
struct Tree* l;
struct Tree* r;
};


struct Tree* rotR( struct Tree* h)
{
if( h == NULL )
return NULL;
struct Tree* x = NULL;
x = h->l;
h->l = x->r;
x->r = h;
return x;
}


struct Tree* rotL( struct Tree* h )
{
if( h == NULL )
return NULL;
struct Tree*x = NULL;
x = h->r;
h->r = x->l;
x->l = h;
return x;
}


struct Tree* insertT( struct Tree* h, int item )
{
if( h == NULL )
{
h = malloc( sizeof(struct Tree) );
if( h == NULL )
{
printf("malloc error\n");
return NULL;
}
else
{
h->item = item;
h->l = NULL;
h->r = NULL;
return h;
}
}
if( h->item > item )
{
h->l = insertT(h->l,item);
h = rotR(h);
}
else
{
h->r = insertT(h->r,item);
h = rotL(h);
}
return h;
}


void travel( struct Tree* t )
{
if( t->l != NULL)
travel(t->l);
printf("%d\n",t->item);
if( t->r != NULL )
travel(t->r);
}


int main( int argc, char* argv[] )
{
struct Tree *t = NULL;
t = insertT(t,8);
t = insertT(t,7);
t = insertT(t,9);
t = insertT(t,6);
t = insertT(t,10);
t = insertT(t,5);
t = insertT(t,11);
t = insertT(t,4);
t = insertT(t,12);
t = insertT(t,3);
t = insertT(t,13);
travel(t);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值