当前位置:网站首页>LeetCode:二叉树展开为链表_114
LeetCode:二叉树展开为链表_114
2022-06-28 20:58:00 【Yuyy】
思路
最终需要的结果是前序遍历,最简单的方式就是递归前序遍历,结果存到队列里,最后再组装。难一点的就是一边遍历一边组装结果,如果是递归,遍历左节点时,将父节点的右节点更改为左节点(题目要求的结果),那么会影响右节点的遍历(已经被替换成左节点了)。所以这里用迭代遍历,将遍历顺序存到了栈里,不用担心修改父节点影响遍历了。
题目
给你二叉树的根结点 root ,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用
TreeNode,其中right子指针指向链表中下一个结点,而左子指针始终为null。 - 展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]示例 2:
输入:root = []
输出:[]示例 3:
输入:root = [0]
输出:[0]提示:
- 树中结点数在范围
[0, 2000]内 -100 <= Node.val <= 100
进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?
Related Topics
- 栈
- 树
- 深度优先搜索
- 链表
- 二叉树
- 905
- 0
代码
public void flatten(TreeNode root) {
if (root == null) {
return;
}
TreeNode pre = null;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
final TreeNode curr = stack.pop();
// 设置上一个节点的right为当前节点,也就是本题需要的结果
if (pre != null) {
pre.left = null;
pre.right = curr;
}
if (curr.right != null) {
stack.push(curr.right);
}
if (curr.left != null) {
stack.push(curr.left);
}
pre = curr;
}
}Post Views: 185
边栏推荐
- ComparisonChain-文件名排序
- Resilience4j retry source code analysis and retry index collection
- Pyechart drawing multiple Y-axis line graphs
- RT thread thread synchronization and thread communication
- Application of Andy s first dictionary (uva10815) Purple Book p112set
- 国产数据库名录一览
- [learning notes] factor analysis
- How to add logs to debug anr problems
- 我也差点“跑路”
- Employee salary management system
猜你喜欢

ThreadLocal principle

LeetCode每日一题——515. 在每个树行中找最大值

视频号如何下载视频?来看超简单方法!

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

【笔记:模拟MOS集成电路】带隙基准(基本原理+电流模+电压模电路详解)

基于 Apache APISIX 的自动化运维平台

Flatten of cnn-lstm
![[Note: analog MOS integrated circuit] bandgap reference (basic principle + current mode + voltage mode circuit explanation)](/img/cd/be62272d465ca990456c222b38df67.png)
[Note: analog MOS integrated circuit] bandgap reference (basic principle + current mode + voltage mode circuit explanation)

MySQL system error occurred 1067

MongoDB——副本集与分片
随机推荐
Is the rapid SSL wildcard certificate genuine in 1981
Is it safe for CICC fortune to open an account? Let's talk about CICC fortune
iterator中的next()为什么要强转?
Leetcode 36. Effective Sudoku (yes, once)
LeetCode每日一题——710. 黑名单中的随机数
题解 The SetStack Computer(UVa12096)紫书P116STL的综合应用
算力时代怎么「算」?「算网融合」先发优势很重要!
关于不完全类型的认识
LeetCode每日一题——522. 最长特殊序列 II
T-test (test whether the mean difference between the two populations is significant)
Keyword long
LeetCode每日一题——324. 摆动排序 II
输入和输出字符型数据
ANR分析--问题1
Embedded dynamic Arabic string conversion LCD display string [thanks for Jianguo ambition]
Binary tree problems
2. integrate filter
Pie (poj3122) super detailed and easy to understand binary introduction
Flask——总结
How to "calculate" in the age of computing power? The first mover advantage of "convergence of computing and networking" is very important!