二叉树最大宽度(递归方式和非递归方式)

求二叉树的最大宽度,该问题可以有两种方式来解决。递归方式和非递归方式。

1、递归方式为先递归求得每一层的宽度,然后就得出了最大宽度所在的层数和该层的节点个数,即为最大宽度。

2、非递归方式为从树的顶层按层计算,从上到下直到叶子节点为止,类似于广度遍历方法,从而计算得出最大宽度所在的层数和该层的节点个数

关于二叉树的定义点击二叉树

#include <iostream>
#include <vector>
using namespace std;

struct TNode
{
	int data;
	TNode *left;
	TNode *right;

	TNode(int _data) : data(_data), left(NULL), right(NULL) {}
};

void showBigWidthTree(const TNode *node);
void showBigWidthTree2(const TNode *node);

int main(void)
{
	TNode root(0);
	TNode node1(1), node2(2), node3(3), node4(4), node5(5);

	root.left = &node1;
	root.right = &node2;
	node1.left = &node3;
	node1.right = &node4;
	node2.right = &node5;

	showBigWidthTree(&root);
	showBigWidthTree2(&root);

	return 0;
}

/// 求树的高度
int heightTree(const TNode *node)
{
	if (!node)
		return 0;

	int hleft = heightTree(node->left);
	int hright = heightTree(node->right);

	return (hleft > hright) ? (hleft + 1) : (hright + 1);
}

/// 计算树给定高度那一层的节点个数,depth:给定所求的是哪一层,cueDepth:当前是哪一层,pnums:存放计算结果,需要提前初始化为0
void dfsNumsOfDepth(const TNode *node, const int depth, int curDepth, int *pnums)
{
	if (!node || curDepth > depth)
		return;
	else if (curDepth < depth)
	{
		dfsNumsOfDepth(node->left, depth, curDepth + 1, pnums);
		dfsNumsOfDepth(node->right, depth, curDepth + 1, pnums);
	}
	else // curDepth == depth
	{
		(*pnums)++;
	}
}

/// 打印树最宽的那一层的高度和节点个数,运用递归的方法
void showBigWidthTree(const TNode *node)
{
	int height = heightTree(node);
	int width = 0, maxWidth = 0, depth = 1;

	for (int i = 1; i <= height; i++)
	{
		width = 0;
		dfsNumsOfDepth(node, i, 1, &width);
		
		if (width > maxWidth)
		{
			maxWidth = width;
			depth = i;
		}
	}

	cout << "max width " << maxWidth << ", his height is " << depth << endl;
}

/// 打印树最宽的那一层的高度和节点个数,运用层级遍历的方法
void showBigWidthTree2(const TNode *node)
{
	vector<const TNode *> v1, v2;
	int width = 1, maxWidth = 1, depth = 0, maxDepth = 0;
	
	v1.push_back(node);
	depth++;
	
	while (!v1.empty())
	{
		v2.clear();
		for (size_t i = 0; i < v1.size(); i++)
		{
			if (v1[i]->left)
				v2.push_back(v1[i]->left);
			if (v1[i]->right)
				v2.push_back(v1[i]->right);
		}
		v1.swap(v2);

		depth++;
		width = v1.size();
		if (width > maxWidth)
		{
			maxWidth = width;
			maxDepth = depth;
		}	
	}

	cout << "max width " << maxWidth << ", his height is " << maxDepth << endl;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值