树形结构--二叉树的遍历算法应用(十九)

在这里插入图片描述


一.遍历算法应用

1.输出二叉树中的结点

void PreOrder(BiTree root)
{
    if(root != NULL)
    {
        printf("%d",root->data); // 假设数据为int类型
        PreOrder(root->RChild); // 遍历左子树
        PreOrder(root->RChild); // 遍历右子树
        //上例为先序遍历,中序遍历和后序遍历,只是printf()位置不同。
    }
}

2.输出二叉树中的叶子结点

void PreOrder(BiTree root)
{
    if(root != NULL)
    {
        if(root->LChild == NULL && root->RChild == NULL)
        {
        printf("%d",root->data);
        }
        PreOrder(root->LChild); 
        PreOrder(root->RChild); 
    }
}

3.统计叶子结点数目

int LeafCount = 0; 

void leaf(BiTree root)
{
    if(root != NULL)
    {
        leaf(root->LChild); 
        leaf(root->RChild);
        if(root->LChild == NULL && root->RChild == NULL)
        {
        LeafCount++;
        }
    }
}

4.建立二叉链表方式存储的二叉树

void CreateBiTree(BiTree * bt)
{
    char ch; 
    ch = getchar(); 
    if(ch == '.')
    {
        *bt = NULL;
    }
    else
    {
        *bt = (BiTree)malloc(sizeof(BiTree));
        (*bt)->data = ch; 
        CreateBiTree(&((*bt)->LChild));
        CreateBiTree(&((*bt)->RChild));
    }
}

5.求二叉树的高度

// 先序遍历求二叉树的高度
int PostTreeDepth(BiTree bt, int h)
{ 
    if(bt != NULL)
    {
        if(h>depth)
        {
            depth = h;
        }
         PostTreeDepth(bt->LChild,h+1);
         PostTreeDepth(bt->RChild,h+1);
    }
}


// 后序遍历求二叉树的高度
int PostTreeDepth(BiTree bt)
{
    int hl,hr,max; 
    if( bt != NULL)
    {
        hl = PostTreeDepth(bt->LChild);
        hr = PostTreeDepth(bt->RChild);
        max = hl>hr?hl:hr; 
        return max+1;
    }
    else return 0;
}

6.按树状打印二叉树

void PrintfTree(BiTree bt,int nLayer)
{
if(bt == NULL)return ;
PrintfTree(bt->RChild,nLayer+1);
for(int i = 0;i<nLayer;i++)
{
    printf(" ");
}
printf("%c\n",bt->data);
PrintfTree(bt->LChild,nLayer+1);
}

若有错误,欢迎指正批评,欢迎评论。
每文一句:欲戴王冠,必承其重。哪有什么好命天赐,不都是一路披荆斩棘才换来的。

发布了74 篇原创文章 · 获赞 180 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Fdog_/article/details/105009469