LeetCode 107. Binary Tree Level Order Traversal II

水题,把每一层的节点存入queue中,val存入vector,vector再存入stack(因为最后结果的顺序是最底层在最前面)。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrderBottom(TreeNode* root) {
13         vector< vector<int> > res;
14         if(!root) return res;
15         stack<vector <int> > stk;
16         queue<TreeNode*> q1, q2;
17         q1.push(root);
18         
19         while(!q1.empty() || !q2.empty()){
20             bool flag = !q1.empty();
21             vector<int> v;
22             if(flag){
23                 while(!q1.empty()){
24                     v.push_back(q1.front()->val);
25                     if(q1.front()->left) {q2.push(q1.front()->left);}
26                     if(q1.front()->right) {q2.push(q1.front()->right);}
27                     q1.pop();
28                 }
29             }
30             else{
31                 while(!q2.empty()){
32                     v.push_back(q2.front()->val);
33                     if(q2.front()->left) q1.push(q2.front()->left);
34                     if(q2.front()->right) q1.push(q2.front()->right);
35                     q2.pop();
36                 }
37             }
38             stk.push(v);
39         }
40         
41         while(!stk.empty()){
42             res.push_back(stk.top());
43             stk.pop();
44         }
45         return res;
46     }
47 };

 

耗时较多,留坑。

posted @ 2016-04-12 20:49  co0oder  阅读(129)  评论(0编辑  收藏  举报