当前位置:网站首页>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
边栏推荐
- T-test (test whether the mean difference between the two populations is significant)
- 应用实践 | 10 亿数据秒级关联,货拉拉基于 Apache Doris 的 OLAP 体系演进(附 PPT 下载)
- with torch. no_ Grad(): reason for using
- Leetcode daily question - 30 Concatenate substrings of all words
- ThreadLocal principle
- Can you make money by speculating in stocks? It's safe to open an account
- 2. integrate filter
- Bitbucket 使用 SSH 拉取仓库失败的问题
- 03.hello_ rust
- Flatten of cnn-lstm
猜你喜欢
oracle delete误删除表数据后如何恢复

数据资产为王,如何解析企业数字化转型与数据资产管理的关系?

Leetcode 36. Effective Sudoku (yes, once)

Bitbucket 使用 SSH 拉取仓库失败的问题

ThreadLocal原理

Query rewriting for opengauss kernel analysis

I almost ran away

MongoDB——副本集与分片

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

Visualization of neural network structure in different frames
随机推荐
Leetcode daily question - 522 Longest special sequence II
【学习笔记】主成分分析法介绍
Win 10 create a gin framework project
mysql-发生系统错误1067
CNN-LSTM的flatten
How to analyze the relationship between enterprise digital transformation and data asset management?
Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer
嵌入式中 动态阿拉伯语字符串 转换 LCD显示字符串【感谢建国雄心】
Leetcode daily question - Sword finger offer II 091 Paint the house
二叉树类题目 力扣
T检验(检验两个总体的均值差异是否显著)
Bitbucket failed to pull the warehouse Using SSH
MySQL system error occurred 1067
Is the rapid SSL wildcard certificate genuine in 1981
关键字long
LeetCode每日一题——522. 最长特殊序列 II
[try to hack] cobalt strike (I)
3. integrate listener
Various types of long
Visualization of neural network structure in different frames