-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path面试题 04.03. 特定深度节点链表.cpp
77 lines (67 loc) · 1.85 KB
/
面试题 04.03. 特定深度节点链表.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/list-of-depth-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/**
* 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) {
// Initial
vector<ListNode*> ret;
if (!tree) {
return ret;
}
queue<TreeNode*> q;
q.push(tree);
while (!q.empty()) {
int len = q.size();
ListNode* head = new ListNode(-1);
ListNode* tail = head;
for (int i = 0; i < len; ++i) {
// Create new list node.
TreeNode* cur = q.front(); q.pop();
tail->next = new ListNode(cur->val);
tail = tail->next;
tail->next = NULL;
// Recursively push into queue.
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
}
ret.push_back(head->next);
}
return ret;
}
};