-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
48 lines (48 loc) · 1.23 KB
/
Solution.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> listOfDepth(TreeNode* tree) {
vector<ListNode*> ans;
if (tree == nullptr) {
return ans;
}
queue<TreeNode*> q;
q.push(tree);
while (!q.empty()) {
int n = q.size();
ListNode* head = new ListNode(-1);
ListNode* tail = head;
for (int i = 0; i < n; ++i) {
TreeNode* front = q.front();
q.pop();
ListNode* node = new ListNode(front->val);
tail->next = node;
tail = node;
if (front->left != nullptr) {
q.push(front->left);
}
if (front->right != nullptr) {
q.push(front->right);
}
}
ans.push_back(head->next);
}
return ans;
}
};