栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++数据结构——计算二叉树最大的宽度

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++数据结构——计算二叉树最大的宽度

计算二叉树最大的宽度

根据带虚结点的先序序列建立二叉树,计算该二叉树最大的宽度(二叉树的最大宽度是指二叉树所有层中结点个数的最大值)并输出。

输入格式:

测试数据有多组,处理到文件尾。每组测试数据在一行中输入一个字符串(不含空格且长度不超过80),表示二叉树的先序遍历序列,其中字符*表示虚结点(对应的子树为空)。

输出格式:

对于每组测试,输出二叉树的最大宽度。输出格式为:“maxWidth: max”,其中max为二叉树的最大宽度值。

输入样例:
HDA**C*B**GF*E***
-+a**xb**-c**d**/e**f**
输出样例:
maxWidth: 3
maxWidth: 4

代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB

解题代码

#include
using namespace std;
string str;
int len;
template
struct treeNode{
	T d;
	treeNode *L_child,*R_child;
};

template
class Tree{
	public:
		treeNode* createNode();
		treeNode* getRoot();
		void getDepth(stack< treeNode* > s,int &num);
	private:
		treeNode *root;
};

template
treeNode* Tree::createNode()
{
	if(len>=str.size()) return NULL;
	T d = str[len++];
	if(d=='*')return NULL;
	treeNode *node = new treeNode();
	node->d=d;
	node->L_child=createNode();
	node->R_child=createNode();
	return node;
}
template
treeNode* Tree::getRoot(){
	return this->root;
}
template
void Tree::getDepth(stack< treeNode* > s,int &num)
{
	stack< treeNode* > s1;
	treeNode* t;
	num=s.size()>num?s.size():num;
	while(!s.empty()){
		t=s.top();
		if(t->L_child!=NULL){
			s1.push(t->L_child);
		}
		if(t->R_child!=NULL){
			s1.push(t->R_child);
		}
		s.pop();
	}
	if(s1.size()==0){
		return;
	}
	getDepth(s1,num);
}
int main()
{
	int num;
	while(cin>>str){
		len=0;
		num=0;
		Tree *tree = new Tree();
		treeNode *root =tree->getRoot();
		root = tree->createNode();
		stack* > s;
		s.push(root);
		tree->getDepth(s,num);
		cout<<"maxWidth: "< 

解题思路

这里的创建树的思路是和之前的思路是一样的,用的是模板类,然后这里,要得到最大深度,意思就是算出每一层的结点数量,然后找到最大的结点数量。协议二哥getDepth函数,然后传递一个栈s,函数中新创建一个空栈s1,将栈s中的所有不为NULL的子结点放入s1中,然后继续递,直至栈空时不再进行递归。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875322.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号