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;
}