【数据结构】基于二叉链表的二叉树最长路径的求解

对着背影说爱祢 提交于 2019-12-02 01:10:46

描述
设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写算法求出该二叉树中第一条最长的路径。

输入
多组数据。每组数据一行,为二叉树的先序序列(序列中元素为‘0’时,表示该结点为空)。当输入只有一个“0”时,输入结束。

输出
每组数据输出一行,第一行为二叉树的最长路径长度,第二行为此路径上从根到叶结点的各结点的值。

样例输入1 复制
abcd00e00f00ig00h00
abd00e00cf00g00
0
样例输出1
4
abcd
3
abd

#include<iostream>
using namespace std;

#define MAX 500

typedef struct binode
{
	char data;
	binode *lchild,*rchild;
}*bitree;

void create(bitree &T)
{
	char ch;
	cin>>ch;
	
	if(ch=='0')
		T=NULL;
	else
	{
		T=new binode;
		T->data=ch;
		create(T->lchild);
		create(T->rchild);
	}
} 

void longestpath(bitree &T,char path[],char longestp[],int &longest,int &len)
{//char path[] 每次循环得到的路径 
//char longestp[]最长路径 
//int &longest最长路径的大小 
//int &len每次循环得到的路径的大小 
	if(T)
	{
		if(T->lchild==NULL&&T->rchild==NULL)
		{
			path[len]=T->data;
			if(len>longest)//如果长于longest就替换 
			{
				for(int i=0;i<=len;i++)
					longestp[i]=path[i];
	
				longest=len;//longest更新 
			}		
		}
		else
		{
			path[len++]=T->data;
			longestpath(T->lchild,path,longestp,longest,len);
			longestpath(T->rchild,path,longestp,longest,len);
			len--;
		}
	}
}

int main()
{
	while(1)
	{
		int i=0;
		char path[MAX],longestp[MAX];
		bitree T;
		
		create(T);
		if(T==NULL)
			break;
			
		int len=0,longest=0;
		longestpath(T,path,longestp,longest,len);
		
		cout<<longest+1<<endl;
		for(int i=0;i<=longest;i++)
			cout<<longestp[i];
		cout<<endl;
	}
	return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!