题目
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
思路
1.类似于二叉树的层次遍历,借助队列和两个计数器
2.区别点是这里需要根据每层节点的值返回链表
相关链接二叉树的层次遍历
实现
/**
* 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) {
vector<ListNode*> res;
queue<TreeNode*> tmp;
int first = 0;
int second = 0;
if (tree == nullptr) {
return res;
}
tmp.push(tree);
++first;
ListNode* head = nullptr;
ListNode* tmp_node = nullptr;
while (first > 0) {
TreeNode* node = tmp.front();
if (head == nullptr) {
head = new ListNode(node->val);
tmp_node = head;
} else {
tmp_node->next = new ListNode(node->val);
tmp_node = tmp_node->next;
}
if (node->left != nullptr) {
tmp.push(node->left);
++second;
}
if (node->right != nullptr) {
tmp.push(node->right);
++second;
}
tmp.pop();
--first;
if (first == 0) {
res.push_back(head);
head = nullptr;
tmp_node = nullptr;
first = second;
second = 0;
}
}
return res;
}
};
该博客介绍了一种算法,用于从给定的二叉树中创建含有特定深度节点的链表。通过类似层次遍历的方法,利用队列和计数器,将每个深度的节点组织成链表,并最终返回所有深度的链表数组。文章提供了示例和思路解析,还提及了与二叉树层次遍历问题的关联。
1144

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



