20170514_建立二叉树+前序遍历+层序遍历+栈+队列

20170514_建立二叉树+前序遍历+层序遍历+栈+队列


//102. Binary Tree Level Order Traversal 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;

const int SIZE=1000;
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x):val(x),left(NULL),right(NULL) {}
};
//建立二叉树
void CreatBiTree(TreeNode * &root)
{
	int ch;
	cin>>ch;
	getchar();
	if(ch == -1)
		root=NULL;
	else
	{
		root=new TreeNode(ch);
		CreatBiTree(root->left);
		CreatBiTree(root->right);
	}
}
//前序遍历二叉树(使用的是栈stack)
void PreOrder(TreeNode *root)
{
	TreeNode *s[SIZE];
	int top=-1;

	while(root != NULL || top != -1)
	{
		while(root != NULL)
		{
			cout<<root->val<<" ";
			s[++top]=root;
			root=root->left;
		}
		if(top != -1)
		{
			root=s[top--];
			root=root->right;
		}
	}
}
//中序遍历二叉树(使用的是队列queue)
void LevelOrder(TreeNode *root)
{
	TreeNode *Q[SIZE];
	int front=0;
	int rear=0;
	if(root==NULL)
		return;
	Q[++rear]=root;
	while(front != rear)
	{
		//auto q=Q[++front];
		TreeNode *q=Q[++front];
		cout<<q->val<<" ";
		if(q->left != NULL)
			Q[++rear]=q->left;
		if(q->right != NULL)
			Q[++rear]=q->right;
	}
}
//层序遍历
class Solution
{
public:
    vector<vector<int>> levelOrder(TreeNode *root)	//二维数组
	{
		vector<vector<int>> result;
		if(root==NULL)
			return result;
		queue<TreeNode *> q;
		q.push(root);
		while(!q.empty())
		{
			int num=q.size();
			vector<int> ivec;
			for(int i=0;i<num;++i)
			{
				TreeNode *top=q.front();
				ivec.push_back(top->val);
				q.pop();
				if(top->left != NULL)
					q.push(top->left);
				if(top->right != NULL)
					q.push(top->right);				
			}
			result.push_back(ivec);
		}

		//输出
		for(auto &cow:result)
		{
			cout<<"[";
			auto beg=cow.begin();
			for(;beg!=--cow.end();++beg)
				cout<<*beg<<",";
			cout<<*beg<<"]";
			cout<<",";
		}
		return result;
	}
};

int main()
{
	TreeNode *root;
	cout<<"依次输入二叉树的结点数据:"<<endl;
	CreatBiTree(root);
	cout<<"二叉树建立完成."<<endl;
	//cout<<"前序遍历二叉树."<<endl;
	//PreOrder(root);
	//cout<<"\n前序遍历二叉树完成."<<endl;
	//cout<<"层序遍历二叉树."<<endl;
	//LevelOrder(root);
	//cout<<"\n层序遍历二叉树完成."<<endl;

	cout<<"Solution类的层序遍历二叉树."<<endl;
	Solution example;
	vector<vector<int>> result;
	result=example.levelOrder(root);
	//for(auto &row:result)
	//	for(auto ele:row)
	//		cout<<ele<<" ";
	cout<<endl;
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值