二叉樹的層序遍歷算法

實現思路:A入隊->然後出隊,出隊時將其左右孩子入隊,循環隊列進行出隊,每次出隊將其左右孩子入隊。當隊列爲空時,整棵樹層序遍歷完畢。

實現過程:

 

代碼:

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

struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) :
		val(x),
		left(NULL),
		right(NULL)
	{

	}
};

vector<vector<int>>levelOrder(TreeNode* root)
{
	vector<vector<int>> res;
	if (!root)
	{
		return res;
	}

	vector<int> vtmp;
	queue<TreeNode*> qu;

	TreeNode * cur;
	int len = 1;

	qu.push(root);

	while (!qu.empty())
	{
		for (int i = 0; i < len; ++i)
		{
			cur = qu.front();
			vtmp.push_back(cur->val);
			cout << cur->val << ' ';
			qu.pop();

			if (cur->left)
			{
				qu.push(cur->left);
			}
			if (cur->right)
			{
				qu.push(cur->right);
			}
		}
		cout << endl;
		res.push_back(vtmp);
		vtmp.clear();
		len = qu.size();
	}
	return res;
}

int main()
{
	TreeNode* root = new TreeNode(3);

	TreeNode* tmpl = new TreeNode(9);
	root->left = tmpl;
	TreeNode* tmpr = new TreeNode(20);
	root->right = tmpr;

	levelOrder(root);
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章