基于二叉链表的二叉树高度的计算

 
 

描述

 

设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写递归算法计算二叉树的高度。


 

输入

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

输出

每组数据分别输出一行,为二叉树的高度。

输入样例 1 

abcd00e00f00ig00h00
abd00e00cf00g00
0

输出样例 1

4
3
#include <iostream>
using namespace std;

int maxi=0;int m=0,n=0;

typedef struct BiTNode
{
	char data;
	struct BiTNode *lchild,*rchild;	
}BiTNode,*BiTree;BiTree temp;

void CreateBiTree(BiTree &T)
{
	char ch;
	cin>>ch;
	if(ch=='0')T=NULL;
	else
	{
		T=new BiTNode;
		T->data=ch;
		CreateBiTree(T->lchild);
		CreateBiTree(T->rchild); 
	}
}

void CreateBiTree(BiTree &T,char ch)
{
	if(ch=='0')T=NULL;
	else
	{
		T=new BiTNode;
		T->data=ch;
		CreateBiTree(T->lchild);
		CreateBiTree(T->rchild); 
	}
}

int Traverse(BiTree T)
{
	if(T)
	{	
		m++;
		if(m>maxi)
		{
			maxi=m;
			temp=T;
		}
	//	cout<<T->data<<":"<<m<<endl; 
		Traverse(T->lchild);
		Traverse(T->rchild);
		m--;	
	}
}

int LonPath(BiTree T,char path[],int pathlen)
{
	int i;
	if(T!=NULL)
	{	
		if(T->lchild==NULL && T->rchild==NULL&&T==temp)
		{
			//cout<<" "<<T->data<<"到根结点路径:"; 
			for(i=0;i<=pathlen-1;i++)
				cout<<path[i];
			cout<<T->data<<endl;
		}
		else
		{
			path[pathlen]=T->data;
			pathlen++;
			LonPath(T->lchild,path,pathlen);
			LonPath(T->rchild,path,pathlen);
			pathlen--;
		}
	}
}

int main()
{
	while(1)
	{
		char ch;char path[100];int pathlen=0;
		cin>>ch;
		if(ch=='0')break;
		BiTree T;
		CreateBiTree(T,ch);
		Traverse(T);
		cout<<maxi<<endl;
		//LonPath(T,path,pathlen);
		maxi=0;m=0;
	}
	return 0;
}
发布了100 篇原创文章 · 获赞 4 · 访问量 3650

猜你喜欢

转载自blog.csdn.net/weixin_43673589/article/details/104437570