英文原文
Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). Return a array containing all the linked lists.
Example:
Input: [1,2,3,4,5,null,7,8] 1 / \ 2 3 / \ \ 4 5 7 / 8 Output: [[1],[2,3],[4,5,7],[8]]
中文题目
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D
,则会创建出 D
个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8] 1 / \ 2 3 / \ \ 4 5 7 / 8 输出:[[1],[2,3],[4,5,7],[8]]
通过代码
高赞题解
/**
* 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) {
queue<TreeNode*> q;
q.push(tree);
vector<ListNode*> ret;
while (!q.empty()) {
int sz = q.size();
ListNode* head = new ListNode(0);
ListNode* p = head;
while (sz--) {
TreeNode* cur = q.front();
q.pop();
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
p->next = new ListNode(cur->val);
p = p->next;
}
ret.push_back(head->next);
delete head;
}
return ret;
}
};
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
25118 | 31178 | 80.6% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|