#include <iostream>
#include <vector>
using namespace std;
template <class T>
struct node{
node *next;
node *prior;
T data;
node(){
}
};
template <class T>//有效期只有一次
struct Q{
node<T>* front;//长见识了
node<T>* end;
Q(){
front=NULL;
end=NULL;
}
void push(T a){
node<T> *n=new node<T>();
n->data=a;
if(!front) {
front=n;
front->prior=NULL;
}
if(!end) {
end=n;
// n-> prior=NULL;
}
else{
n->prior=end;
end->next=n;
end=n;
}
end->next=NULL;
}
void pop(){
if(!front) {
cout<<"error ::the queue is NULL"<<endl;
return ;
}
node<T> *n;
n=front;
front=n->next;
if(front)
front->prior=NULL;
else end=NULL;
delete(n);
}
T visitTop(){
if(front)
return front->data;
else {
cout<<"error";
return NULL;
}
}
bool empty(){
if(!front) return 1;
else return 0;
}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct Node {
TreeNode *u;
int level;
Node(TreeNode *a=NULL,int b=0){
u=a;
level=b;
}
};
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > vv;
Q<Node> q;
vector<int> E;
if(root!=NULL)
{
q.push(Node(root,0));
}
while(!q.empty())
{
Node temp=q.visitTop();
q.pop();
int level=temp.level;
if(vv.size()==level){//NULL树的特殊处理
vv.push_back(E);//NULL树的特殊处理
}//NULL树的特殊处理
if(temp.u->left) {q.push(Node(temp.u->left,level+1));}
if(temp.u->right) {q.push(Node(temp.u->right,level+1));}
vv[level].push_back(temp.u->val);
}//很傻的方法,要多看看师傅的代码
return vv;
}
};
int main ()
{
TreeNode root(1);
Solution s;
s.levelOrder(&root);
return 0;
}
师傅博客:http://ofpsxx.com