题
面试题 04.03. 特定深度节点链表
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
解题思路
使用一个 nextStart 来记录每一层的开始节点
代码
class Solution
{
public:
vector<ListNode *> listOfDepth(TreeNode *tree)
{
vector<ListNode *> result;
queue<TreeNode *> q;
ListNode *head;
q.push(tree);
TreeNode *nextStart = tree;
while (!q.empty())
{
auto node = q.front();
q.pop();
if (node == nextStart)
{
head = new ListNode(node->val);
result.push_back(head);
nextStart = NULL;
}else{
auto p = new ListNode(node->val);
head->next = p;
head = p;
}
if (node->left)
{
if (!nextStart)
{
nextStart = node->left;
}
q.push(node->left);
}
if (node->right)
{
if (!nextStart)
{
nextStart = node->right;
}
q.push(node->right);
}
}
return result;
}
};
本文介绍了一种解决二叉树按深度创建链表的问题,通过使用队列和nextStart变量,实现从根节点到指定深度的所有节点链接。适用于面试和技术挑战。
754

被折叠的 条评论
为什么被折叠?



