关于二叉树的一些练习
- 一、求一个二叉排序树的最大值
- 二、求一个二叉树的高度
- 三、平衡操作
- 四、输出度为1的结点
- 五、二叉树的宽度
一、求一个二叉排序树的最大值
void max(BiNode *root)
{
if(root == NULL)
{
return;
}
BiNode *p = root;
while(p->rchild)
{
p = p->rchild;
}
printf("%d\n",p->data);
}
二、求一个二叉树的高度
int getheight(BiNode *root)
{
int leftheight,rightheight,maxheight;
if(root != NULL)
{
leftheight = getheight(root->lchild);
rightheight = getheight(root->rchild);
maxheight = leftheight > rightheight ? leftheight : rightheight;
return maxheight + 1;
}
else
{
return 0;
}
}
三、平衡操作
BiNode *ll_route(BiNode *x)
{
BiNode *k = x->lchild;
x->lchild = k->rchild;
k->rchild = x;
x->h = getheight(x);
k->h = getheight(k);
return k;
}
BiNode *rr_route(BiNode *x)
{
BiNode *k = x->rchild;
x->rchild = k->lchild;
k->lchild = x;
x->h = getheight(x);
k->h = getheight(k);
return k;
}
BiNode *lr_route(BiNode *x)
{
x->lchild = rr_route(x->lchild);
x = ll_route(x);
return x;
}
BiNode *rl_route(BiNode *x)
{
x->rchild = ll_route(x->rchild);
x = rr_route(x);
return x;
}
四、输出度为1的结点
void level_one(BiNode *root)
{
if(root == NULL)
{
return;
}
SeqQue *q = initser(1024);
int num = 0;
SeqQuein(q,root);
printf("度为1的结点为:");
while(!SeqQueisEmpty(q))
{
Qelmetype x;
SeqQueout(q,&x);
if((x->lchild != NULL && x->rchild == NULL)||(x->lchild == NULL && x->rchild != NULL))
{
printf("%d ",x->data);
num++;
}
if(x->lchild)
{
SeqQuein(q.x->lchild);
}
if(x->rchild)
{
SeqQuein(q,x->rchild);
}
}
printf("\n度为一的结点个数为:%d\n",num);
destroy(q);
return;
}
五、二叉树的宽度
int biwidth(BiNode *root)
{
if(root == NULL)
{
return 0;
}
int width,max;
int i = 1;max_i;
BiNode *p = NULL;
SeqQue *q = initseq(1024);
SeqQuein(q,root);
width = 1;
max = width;
max_i = 1;
while(!SeqQueisEmpty(q))
{
SeqQueout(q,&p);
width--;
if(p->lchild)
{
SeqQuein(q,p->lchild);
}
if(p->rchild)
{
SeqQuein(q,p->rchild);
}
if(width == 0)
{
width = q->nowlen;
i++;
if(max < width)
{
max = width;
max-i = i;
}
}
}
printf("二叉树层次 %d 的宽度最大\n", max_i);
destroy(q);
return max;
}