Basic question. Use a queue to store Node, use two numbers to record current level node numbers and next level node numbers.

 

 1 /**
 2  * Definition for binary tree
 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> > levelOrder(TreeNode *root) {
13         vector<vector<int> > result;
14         vector<int> level;
15         if (!root) return result;
16         int current = 1, future = 0;
17         queue<TreeNode *> q;
18         q.push(root);
19         while(!q.empty()) {
20             TreeNode *tmp = q.front();
21             q.pop();
22             current--;
23             if (tmp->left) {
24                 q.push(tmp->left);
25                 future++;
26             }
27             if (tmp->right) {
28                 q.push(tmp->right);
29                 future++;
30             }
31             level.push_back(tmp->val);
32             if (!current) {
33                 current = future;
34                 future = 0;
35                 result.push_back(level);
36                 level.clear();
37             }
38         }
39         return result;
40     }
41 };

 

posted on 2015-03-18 07:44  keepshuatishuati  阅读(102)  评论(0编辑  收藏  举报