leetcode 114. Flatten Binary Tree to Linked List 二叉树展开为链表(简单)
2023-09-11 14:22:52 时间
一、题目大意
给你二叉树的根结点 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) 额外空间)展开这棵树吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
思路:非迭代版实现,从根节点开始出发,先检测其左子节点是否存在,如存在则将根节点和其右节点断开,将左子节点及其后面所有结构一起连接到右子节点的位置,把原右子节点连到原左子节点为最后面的右子节点之后。
三、解题方法
3.1 Java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
// 下面再来看非迭代版本的实现,这个方法是从根节点开始出发,先检测其左子结点是否存在,如存在则将根节点和其右子节点断开,
// 将左子结点及其后面所有结构一起连到原右子节点的位置,把原右子节点连到元左子结点最后面的右子节点之后。代码如下:
TreeNode cur = root;
while (cur != null) {
if (cur.left != null) {
TreeNode p = cur.left;
while (p.right != null) {
p = p.right;
}
p.right = cur.right;
cur.right = cur.left;
cur.left = null;
}
cur = cur.right;
}
}
}
四、总结小记
- 2022/9/6 按起了葫芦起了瓢;都不愿意写文档,全凭个人经验来推动
相关文章
- 别迷茫了,师兄告诉你怎么刷 LeetCode
- G 面经 && Leetcode: Longest Repeating Character Replacement
- Leetcode: Largest Divisible Subset
- Leetcode: Remove Linked List Elements
- Leetcode: Merge Intervals
- Leetcode: Reverse Linked List II
- Leetcode: Rotate List
- Leetcode: Valid Parentheses
- leetcode | Reverse Nodes in k-Group
- 【Java】List去重 / 删除ArrayList中重复元素,保持顺序 / 提取两个list中不同的元素
- LeetCode 344. 反转字符串
- 【LeetCode】167. Two Sum II - Input array is sorted
- 【LeetCode】97. Interleaving String
- 【LeetCode】114. Flatten Binary Tree to Linked List
- Leetcode[33]-Search in Rotated Sorted Array
- Insertion Sort List -- leetcode
- LeetCode 5. 最长回文子串
- [LeetCode] 1019. Next Greater Node In Linked List 链表中的下一个较大的结点
- [LeetCode] 479. Largest Palindrome Product 最大回文串乘积
- [LeetCode] Reverse Linked List 倒置链表
- [LeetCode] 145. Binary Tree Postorder Traversal 二叉树的后序遍历
- [LeetCode] 141. Linked List Cycle 单链表中的环