数据结构——补充二叉树的一些算法程序

 

1.以二叉链表为存储结构,编写算法交换每个结点的左右子树。

void Swap(BinTree bt)
{
    BinTree t;
    if(bt->lchild!=NULL&&bt->rchild!=NULL)
    {
        Swap(bt->lchild);
        Swap(bt->rchild);
        t=bt->lchild;
        bt->lchild=bt->rchild;
        bt->rchild=t;
    }
}

 

2.以二叉链表为存储结构,编写算法求出二叉树中度为1的结点个数。

counts=0;
void Count(BinTree bt,int *counts)
{
    if(bt->lchild!=NULL&&bt->rchild==NULL)
    {
        counts++;
    }
    else if(bt->rchild!=NULL&&bt->lchild==NULL)
    {
        counts++;
    }
    Count(bt->lchild,counts);
    Count(bt->rchild,counts);
}

ps:这个思路参考求二叉树叶子结点的那个代码来的。

 

3.以二叉链表为存储结构,编写算法求二叉树中结点x的双亲

void FindPr(BinTree bt,BinTree *P,char x)
{
    if(bt)
    {
        if(bt->lchild!=NULL)
        {
            if(bt->lchild->data==x)
            {
                p=bt;
                return ;
            }
        }
        else if(bt->rchild!=NULL)
        {
            if(bt->rchild->data==x)
            {
                p=bt;
                return ;
            }
        }
        FindPr(bt->lchild,x);
        FindPr(bt->rchild,x);
    }
}

 

4.以二叉链表为存储结构,编写算法复制一棵二叉树

void Copy(BinTree bt,BinTree *s)
{
    BinTree lptr, rptr;
    if(!bt)//bt=NULL
    {
        s=NULL;
    }
    else
    {
        Copy(bt->lchild,lptr);
        Copy(bt->rchild,rptr);
        s=(BiTree*)malloc(sizeof(BiTree) );
        s->data=bt->data;
        s->lchild=lptr;
        s->rchild=rptr;
    }
}

 

转载于:https://www.cnblogs.com/wkfvawl/p/10065290.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值