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

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