题目
给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 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;
}
};