forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevelOrder.cpp
More file actions
28 lines (28 loc) · 870 Bytes
/
levelOrder.cpp
File metadata and controls
28 lines (28 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > res;
if (root == NULL) return res;
deque<pair<TreeNode, int> > mm;
mm.push_back(make_pair(*root, 0));
while (!mm.empty()) {
TreeNode now = mm.front().first;
int idx = mm.front().second;
mm.pop_front();
if (res.size() <= idx) res.push_back(vector<int>());
res[idx].push_back(now.val);
if (now.left != NULL) mm.push_back(make_pair(*now.left, idx + 1));
if (now.right != NULL) mm.push_back(make_pair(*now.right, idx + 1));
}
return res;
}
};