1.题目
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
层序遍历加链表记录
class Solution
{
public:
vector<ListNode*> listOfDepth(TreeNode* tree)
{
vector<ListNode*> res;
if(!tree) return res;
queue<TreeNode*> q;
q.push(tree);
while(!q.empty())
{
ListNode* head=new ListNode(-1);//每层设置一个链表头节点
ListNode* x=head;
int size=q.size();
for(int i=0; i<size; ++i)
{
TreeNode* t=q.front();
ListNode* tl=new ListNode(t->val);
x->next=tl;
x=x->next;
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(head->next);
}
return res;
}
};