二叉树的最长路径

创建一个二叉树,然后找到二叉树中最长的路径,并输出。

代码如下

#include<stdio.h>
#include<bits/stdc++.h> 
#define MAX  200
typedef char TElemType;
typedef int status; 
typedef struct BiNode
{
    TElemType data;
    struct BiNode *lchild;
    struct BiNode *rchild;
}BiNode,*BiTree;
void CreateBiTree(BiTree &T)//二叉树的先序创建 
{
    TElemType ch;
    scanf("%c",&ch);
    if(ch=='#')
        T=NULL;
    else 
    {
        T=(BiNode*)malloc(sizeof(BiNode));
        if(!T)
            exit(-1);
        T->data=ch;
        CreateBiTree(T->lchild);
        CreateBiTree(T->rchild);
    }
}
void longest_path(BiTree T,char *path,int &len,char *longestpath,int &longest_len)
{
    if(T!=NULL)
    {
        path[len++]=T->data;
        if(T->lchild==NULL&&T->rchild==NULL)//当遇到叶子结点时,该条路径完毕 
        {
            if(len-1>longest_len)//如果长于longest_len就替换 
            {
                for(int j=0;j<=len-1;j++)
                {
                    longestpath[j]=path[j];
                }
                longest_len=len-1;//longest_len更新 
            }
        }
            longest_path(T->lchild ,path,len,longestpath,longest_len);
            longest_path(T->rchild ,path,len,longestpath,longest_len);
            len--;
    }
}
int main()
{
    BiTree T;
    printf("创建树输入树T的先序序列(其中使用#代表空节点)\n");
    CreateBiTree(T);
    char path[MAX]={0};
    char longestpath[MAX]={0};
    int len=0;
    int longest_len=0;
    longest_path(T,path,len,longestpath,longest_len);
    printf("第一条最长的路径长度为:%d\n",longest_len);
    printf("路径为:"); 
    for(int i=0;i<=longest_len;i++)
    {
        printf("%c ",longestpath[i]);
    }    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值