leetcode-107. 二叉树的层序遍历 II
题目:
代码:
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef struct TreeNode{
int val;
struct TreeNode *left,*right;
}TreeNode,*BiTree;
void create(BiTree &T){
char ch;
cin>>ch;
if(ch=='#'){
T=NULL;
return;
}
T=new TreeNode;
T->val=ch-'0';
create(T->left);
create(T->right);
}
vector<vector<int> > levelOrderBottom(TreeNode* root) {
vector<vector<int> > res;
if(!root){
return res;
}
queue<TreeNode *>q;
q.push(root);
while(!q.empty()){
vector<int> lever;
int size=q.size();
for(int i=0;i<size;i++){
TreeNode *T=q.front();
q.pop();
lever.push_back(T->val);
if(T->left){
q.push(T->left);
}
if(T->right){
q.push(T->right);
}
}
res.push_back(lever);
}
reverse(res.begin(),res.end());
return res;
}
int main(){
vector<vector<int> >res;
TreeNode* root;
create(root);
res=levelOrderBottom(root);
for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++){
cout<<res[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
|