5.1.4—二叉树的遍历—Binary Tree Level Order Traversal

描述
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from le to right, level by
level).
For example: Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

#include "BinaryTree.h"
#include <stack>
#include<queue>
#include<vector>
using namespace std;
//===二叉树的层次遍历
vector<vector<int>> LevelTraversal(BinaryTreeNode *proot)
{
	queue<BinaryTreeNode*>temp;
	vector<int> tempres;//记录所有数字
	vector<int> num;//记录每一层的个数

	temp.push(proot);
	int Initial = 1;
	num.push_back(Initial);

	while (!temp.empty())
	{
		int cnt = 0;
		for (int i = 0; i < Initial; i++)
		{
			BinaryTreeNode *p = temp.front();
			tempres.push_back(p->m_nValue);
			temp.pop();
			if (p->m_pLeft)
			{
				temp.push(p->m_pLeft);
				cnt++;
			}
			if (p->m_pRight)
			{
				temp.push(p->m_pRight);
				cnt++;
			}
		}
		Initial = cnt;
		if (Initial!=0)
			num.push_back(Initial);
	}
	//====================
	vector<vector<int>> res;
	int cnt = 0;
	for (int i = 0; i < num.size();i++)
	{
		vector<int> cahe;
		for (int j =cnt; j < cnt+num[i]; j++)
			cahe.push_back(tempres[j]);
		
		cnt += num[i];
		res.push_back(cahe);
	}
	return res;
}
// ====================测试代码====================
//            8
//        6      10
//       5 7    9  11
int main()
{
	BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
	BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
	BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
	BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
	BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);

	ConnectTreeNodes(pNode8, pNode6, pNode10);
	ConnectTreeNodes(pNode6, pNode5, pNode7);
	ConnectTreeNodes(pNode10, pNode9, pNode11);
	//===
	//PrintTree(pNode8);
	//===
	vector<vector<int>> res = LevelTraversal(pNode8);
	for (int i = 0; i < res.size(); i++)
	{
		for (int j = 0; j < res[i].size(); j++)
			cout << res[i][j] << " ";
		cout << endl;
	}

	DestroyTree(pNode8);
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值