当前位置:网站首页>Interview question 04.03 Specific depth node linked list (medium)
Interview question 04.03 Specific depth node linked list (medium)
2022-04-22 08:40:00 【weixin_ forty-six million two hundred and seventy-two thousand 】
Interview questions 04.03. Specific depth node list
Given a binary tree , Design an algorithm , Create a linked list containing all nodes at a certain depth ( such as , If the depth of a tree is D, Then create D A linked list ). Returns an array containing a linked list of all depths .
Example :
Input :[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
Output :[[1],[2,3],[4,5,7],[8]]
Ideas
It can be seen that the linked list is established layer by layer , It's natural to think of using queues to traverse , Pop up elements one layer at a time , We create the node of the linked list according to the value of the element . However, the chain header node itself will participate in backward traversal , So we also need to create a virtual head node before the loop of the first layer, pointing to the real head node
Source code
class Solution {
public:
vector<ListNode*> listOfDepth(TreeNode* tree) {
vector<ListNode*> v;
if (tree == nullptr) {
return v;
}
queue<TreeNode*> queue;
queue.push(tree);
while (!queue.empty()) {
int size = queue.size();
ListNode* virtual_head = new ListNode();// Create a virtual head node to point to the real head node
ListNode* head = virtual_head;// Create a header node , The follow-up will continue to move forward
for (int i=0; i<size; i++) {
TreeNode* node = queue.front();
queue.pop();
head->next = new ListNode(node->val);// Create a linked list node with the same value , And let the head node point to it
head = head->next;// Head node backward
if (node->left) {
queue.push(node->left);// Push the
}
if (node->right) {
queue.push(node->right);// Push the
}
}
v.push_back(virtual_head->next);// Create a linked list one layer at a time , Push the head node of the linked list into vector
}
return v;
}
};
版权声明
本文为[weixin_ forty-six million two hundred and seventy-two thousand ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220742290822.html
边栏推荐
猜你喜欢
随机推荐
cesium中实现楼层分解动画
oracle数据库表空间容量查询及扩容
kubernetes—实战入门
100. 相同的树(Easy)
Shell command script
Client server communication project 1
jmu-枚举WeekDay
Fluent listview loads more
又来一个上三角数字三角形
客户端与服务器项目3
leaflet、cesium加载百度地图,加载自定义样式百度地图
226. 翻转二叉树(Easy)
累加器
The map cutter can cut the picture into tile data. Its main purpose is to cut the high-definition satellite image into tile map. It can be used for offline map development based on Mercator coordinate
235. 二叉搜索树的最近公共祖先(Easy)
Fresco简单的使用—SimpleDraweeView
指针和字符串
express项目将jade模板改为art-template
JMU enumeration weekday
客户端与服务器通信项目2







![[Dahua cloud native] micro service chapter - service mode of five-star hotels](/img/fc/be18f39e4aa653efa8603ab63ff3f1.png)

