给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
例:
输入:[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
class Solution {
public:
vector<ListNode*> listOfDepth(TreeNode* tree) {
if(!tree)
return {};
queue<TreeNode*> q;
vector<ListNode*> ans;
q.push(tree);
int size;
TreeNode* tp;
ListNode* head, *cur;
bool hashead;
while(!q.empty())
{
size = q.size();
hashead = false;
while(size--)
{
tp = q.front();
q.pop();
if(!hashead)
{
head = new ListNode(tp->val);
cur = head;
hashead = true;
}
else
{
cur->next = new ListNode(tp->val);
cur = cur->next;
}
if(tp->left)
q.push(tp->left);
if(tp->right)
q.push(tp->right);
}
ans.push_back(head);
}
return ans;
}
};