File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ // Start typing your C/C++ solution below
14
+ // DO NOT write int main() function
15
+ if (!root)return vector<vector<int > >();
16
+ queue<TreeNode *>q;
17
+ q.push (root);
18
+ int node_in_now_level=1 ;
19
+ int node_in_next_level=0 ;
20
+ vector<vector<int > >ans;
21
+ vector<int >now;
22
+ while (!q.empty ())
23
+ {
24
+ TreeNode *p=q.front ();
25
+ q.pop ();
26
+ now.push_back (p->val );
27
+ node_in_now_level--;
28
+ if (p->left )
29
+ {
30
+ q.push (p->left );
31
+ node_in_next_level++;
32
+ }
33
+ if (p->right )
34
+ {
35
+ q.push (p->right );
36
+ node_in_next_level++;
37
+ }
38
+ if (!node_in_now_level)
39
+ {
40
+ ans.push_back (now);
41
+ now.clear ();
42
+ swap (node_in_now_level,node_in_next_level);
43
+ }
44
+ }
45
+ return ans;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments