当前位置:网站首页>LeetCode116. 填充每个节点的下一个右侧节点指针
LeetCode116. 填充每个节点的下一个右侧节点指针
2022-06-28 20:59:00 【Yuyy】
本文最后更新于 484 天前,其中的信息可能已经有所发展或是发生改变。
一、思路
经过画图发现,儿子之间连接没问题。但是不同父亲的孙子连接有问题,解决一个倒还好,巧妙的是经过递归,可以解决所有这类问题。 总是想着把问题分治,但分治完了却没想到可以还原回去。。。
二、问题
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
输入:root = [1,2,3,4,5,6,7]
输出:[1,#,2,3,#,4,5,6,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。提示:
- 树中节点的数量少于
4096 -1000 <= node.val <= 1000
Related Topics
- 树
- 深度优先搜索
- 广度优先搜索
\n
- 404
- 0
三、代码
public Node connect(Node root) {
if (root == null) {
return null;
}
convert(root.left, root.right);
return root;
}
private void convert(Node left, Node right) {
if (left == null || right == null) {
return;
}
left.next = right;
convert(left.left, left.right);
convert(right.left, right.right);
convert(left.right, right.left);
}Post Views: 297
边栏推荐
- Mongodb - replica set and sharding
- On the complexity of software development and the way to improve its efficiency
- Is it safe to open a dig money account? Is it reliable?
- [book club issue 13] packaging format of video files
- Win 10 create a gin framework project
- 员工薪资管理系统
- Real number operation
- Leetcode daily question - 30 Concatenate substrings of all words
- Binary tree problems
- RT thread thread synchronization and thread communication
猜你喜欢

On the complexity of software development and the way to improve its efficiency

ref属性,props配置,mixin混入,插件,scoped样式

RT thread thread synchronization and thread communication

【筆記:模擬MOS集成電路】帶隙基准(基本原理+電流模+電壓模電路詳解)

The principle and source code analysis of Lucene index construction

CNN-LSTM的flatten

with torch.no_grad():的使用原因
How to recover after Oracle delete accidentally deletes table data

Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer

ThreadLocal principle
随机推荐
接口用例设计
T检验(检验两个总体的均值差异是否显著)
The further application of Li Kou tree
Visualization of neural network structure in different frames
Flask——总结
实型数运算
我也差点“跑路”
Explanation of memory dump triggered by software watchdog and anr
市值1200亿美金,老牌财税巨头Intuit是如何做到的?
券商公司开户哪个最靠谱最安全呢
LeetCode每日一题——30. 串联所有单词的子串
Lucene构建索引的原理及源代码分析
学习太极创客 — MQTT 第二章(八)ESP8266 MQTT 用户密码认证
Comparisonchain file name sort
【学习笔记】聚类分析
Bitbucket 使用 SSH 拉取仓库失败的问题
Which is the most reliable and safe for a securities company to open an account
不同框架的绘制神经网络结构可视化
How to "calculate" in the age of computing power? The first mover advantage of "convergence of computing and networking" is very important!
Bitbucket failed to pull the warehouse Using SSH