当前位置:网站首页>[algorithm leetcode] interview question 04.03 Specific depth node linked list (Multilingual Implementation)
[algorithm leetcode] interview question 04.03 Specific depth node linked list (Multilingual Implementation)
2022-07-04 14:27:00 【White hat of the second leader】
List of articles
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 .
Examples 1:
Input :
[1,2,3,4,5,null,7,8]
1
/ \
2 3
/ \ \
4 5 7
/
8
Output :
[[1],[2,3],[4,5,7],[8]]
analysis
- Facing this algorithm problem , The second leader was lost in thought .
- If you are familiar with binary trees and linked lists , You will understand that it is actually the sequence traversal of binary tree , Each layer is combined into a linked list .
Answer key
rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn list_of_depth(tree: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<Box<ListNode>>> {
let mut ans: Vec<Option<Box<ListNode>>> = Vec::new();
let mut queue = std::collections::VecDeque::new();
queue.push_back(tree);
while !queue.is_empty() {
let mut head = Some(Box::new(ListNode::new(0)));
let mut tail = head.as_mut();
let size = queue.len();
for _ in 0..size {
let node = queue.pop_front().unwrap().unwrap();
let mut node = node.borrow_mut();
if node.left.is_some() {
queue.push_back(node.left.take());
}
if node.right.is_some() {
queue.push_back(node.right.take());
}
tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(node.val)));
tail = tail.unwrap().next.as_mut();
}
ans.push(head.as_mut().unwrap().next.take());
}
ans
}
}
go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */
func listOfDepth(tree *TreeNode) []*ListNode {
var ans []*ListNode
queue := []*TreeNode{
tree}
for len(queue) > 0 {
head := &ListNode{
}
tail := head
size := len(queue)
for i := 0; i < size; i++ {
node := queue[i]
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
tail.Next = &ListNode{
Val: node.Val}
tail = tail.Next
}
ans = append(ans, head.Next)
queue = queue[size:]
}
return ans
}
typescript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */
function listOfDepth(tree: TreeNode | null): Array<ListNode | null> {
const ans = [];
const queue = [tree];
while (queue.length > 0) {
const head = new ListNode();
let tail = head;
const size = queue.length;
for (let i = 0; i < size; ++i) {
const {
val, left, right } = queue.shift();
left && queue.push(left);
right && queue.push(right);
tail.next = new ListNode(val);
tail = tail.next;
}
ans.push(head.next);
}
return ans;
};
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
ans = []
q = collections.deque()
q.append(tree)
while len(q) > 0:
head = ListNode()
tail = head
size = len(q)
for _ in range(size):
node = q.popleft()
node.left and q.append(node.left)
node.right and q.append(node.right)
tail.next = ListNode(node.val)
tail = tail.next
ans.append(head.next)
return ans
c
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
int getDepth(struct TreeNode* tree) {
if (!tree) {
return 0;
}
int leftDepth = getDepth(tree->left);
int rightDepth = getDepth(tree->right);
return fmax(leftDepth, rightDepth) + 1;
}
/** * Note: The returned array must be malloced, assume caller calls free(). */
struct ListNode** listOfDepth(struct TreeNode* tree, int* returnSize){
int depth = getDepth(tree);
struct ListNode **ans = malloc(depth * sizeof(struct ListNode *));
*returnSize = 0;
struct TreeNode *queue[(int) pow(2, depth) - 1];
queue[0] = tree;
int start = 0;
int end = 1;
while (start < end) {
struct ListNode head = {
};
struct ListNode *tail = &head;
int curEnd = end;
while (start < curEnd) {
struct TreeNode *node = queue[start++];
if (node->left) {
queue[end++] = node->left;
}
if (node->right) {
queue[end++] = node->right;
}
tail->next = malloc(sizeof(struct ListNode));
tail->next->val = node->val;
tail->next->next = NULL;
tail = tail->next;
}
ans[(*returnSize)++] = head.next;
}
return ans;
}
c++
/** * 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 *> ans;
queue<TreeNode *> q;
q.push(tree);
while (q.size() > 0) {
ListNode head = ListNode(0);
ListNode *tail = &head;
int size = q.size();
for (int i = 0; i < size; ++i) {
TreeNode *node = q.front();
q.pop();
if (node->left != NULL) {
q.push(node->left);
}
if (node->right != NULL) {
q.push(node->right);
}
tail->next = new ListNode(node->val);
tail = tail->next;
}
ans.emplace_back(head.next);
}
return ans;
}
};
java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode[] listOfDepth(TreeNode tree) {
List<ListNode> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(tree);
while (!queue.isEmpty()) {
ListNode head = new ListNode();
ListNode tail = head;
int size = queue.size();
for (int i = 0; i < size; ++i) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
tail.next = new ListNode(node.val);
tail = tail.next;
}
list.add(head.next);
}
ListNode[] ans = new ListNode[list.size()];
list.toArray(ans);
return ans;
}
}
Original title transmission gate :https://leetcode.cn/problems/list-of-depth-lcci/submissions/
Thank you very much for reading this article ~
welcome 【 give the thumbs-up 】【 Collection 】【 Comment on 】~
It's not hard to give up , But persistence must be cool ~
I hope all of us can make a little progress every day ~
This paper is written by The white hat of the second leader :https://le-yi.blog.csdn.net/ Original blog ~
边栏推荐
- Data warehouse interview question preparation
- No servers available for service: xxxx
- 数据仓库面试问题准备
- How to package QT and share exe
- 测试流程整理(2)
- 测试流程整理(3)
- 第十六章 字符串本地化和消息字典(二)
- scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
- R语言dplyr包summarise_if函数计算dataframe数据中所有数值数据列的均值和中位数、基于条件进行数据汇总分析(Summarize all Numeric Variables)
- Leetcode t49: grouping of alphabetic words
猜你喜欢

Excel quickly merges multiple rows of data

Detailed index of MySQL

为什么图片传输要使用base64编码

基于51单片机的超声波测距仪

一文概览2D人体姿态估计

Use of tiledlayout function in MATLAB

DDD application and practice of domestic hotel transactions -- Code

Data warehouse interview question preparation

Intelligence d'affaires bi analyse financière, analyse financière au sens étroit et analyse financière au sens large sont - ils différents?

电商系统中红包活动设计
随机推荐
Leetcode T47: 全排列II
Migration from go vendor project to mod project
【信息检索】链接分析
Popular framework: the use of glide
R语言使用epiDisplay包的followup.plot函数可视化多个ID(病例)监测指标的纵向随访图、使用stress.col参数指定强调线的id子集的颜色(色彩)
Digi XBee 3 RF: 4个协议,3种封装,10个大功能
How to operate and invest games on behalf of others at sea
Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]
Map of mL: Based on Boston house price regression prediction data set, an interpretable case is realized by using the map value to the LIR linear regression model
Fs4059c is a 5V input boost charging 12.6v1.2a. Inputting a small current to three lithium battery charging chips will not pull it dead. The temperature is 60 ° and 1000-1100ma is recommended
flink sql-client.sh 使用教程
R language ggplot2 visualization: gganimate package creates animated graph (GIF) and uses anim_ The save function saves the GIF visual animation
Intelligence d'affaires bi analyse financière, analyse financière au sens étroit et analyse financière au sens large sont - ils différents?
sql优化之explain
如何游戏出海代运营、游戏出海代投
R语言ggplot2可视化:gganimate包创建动态折线图动画(gif)、使用transition_reveal函数在动画中沿给定维度逐步显示数据
Nowcoder rearrange linked list
去除重複字母[貪心+單調棧(用數組+len來維持單調序列)]
Talk about 10 tips to ensure thread safety
redis 日常笔记