AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > 数据结构

二叉树基本操作的程序实现

51自学网 http://www.51zixue.net

#include"Bintree.h"
/*******************************************/
/*      递归法将二叉树的左右子树互换       */
/*******************************************/
void Exchange1(Bintree t)
{
    Bintree temp;
    if(t)
    {
        Exchange1(t->lchild);
        Exchange1(t->rchild);
        temp=t->lchild;
        t->lchild=t->rchild;
        t->rchild=temp;
    }
}
/*******************************************/
/*      非递归法将二叉树的左右子树互换     */
/*******************************************/
void Exchange2(Bintree t)
{
    Bintree temp;
    stack s;
    s.top=0;
    while(t||s.top)
    {
        if(t)
        {
            s.data[s.top++]=t;
            temp=t->lchild;
            t->lchild=t->rchild;
            t->rchild=temp;
            t=t->lchild;
        }
        else
        {
            t=s.data[--s.top]->rchild;
        }

    }
}
int main()
{
    Bintree t;
    Creat_Bintree(&t);
    Exchange2(t);
    Inorder2(t);
    return 0;
}

 

#include"Bintree.h"
/*******************************************/
/*        递归法求叶子结点个数             */
/*******************************************/
int Leaves_Num1(Bintree t)
{
    if(t)
    {
        if(t->lchild==NULL&&t->rchild==NULL)
        {
            return 1;
        }
        return Leaves_Num1(t->lchild)+Leaves_Num1(t->rchild);
    }
    return 0;
}

/*******************************************/
/*        非递归法求叶子结点个数             */
/*******************************************/
int Leaves_Num2(Bintree t)
{
    int count=0;
    stack s;
    s.top=0;
    while(t||s.top>0)
    {
        if(t)
        {
             s.data[s.top++]=t;
             if(t->lchild==NULL&&t->rchild==NULL)
             {

                count++;
             }
             t=t->lchild;
        }
        else
        {
            t=s.data[--s.top]->rchild;
        }
    }
    return count;
}

        
int main()
{
    int count=0;
    Bintree t;
    Creat_Bintree(&t);
    count=Leaves_Num2(t);
    printf("该二叉树的叶子结点数为:%d/n",count);
    return 0;
}

 
 

上一篇:五子棋算法  下一篇:数据结构与算法基本程序合集