【LeetCode】二叉树展开为链表 [M](Morris遍历)
2023-09-27 14:19:51 时间
一、题目
给你二叉树的根结点 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)
额外空间)展开这棵树吗?
二、代码
/**
* 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;
// 当前遍历到的cur节点的上一个遍历到的节点(按先序遍历顺序)
TreeNode pre = null;
// 当前节点左子树的最右子节点
TreeNode mostRight = null;
// 经典的Morris先序遍历
while (cur != null) {
// 来到当前节点的左子树
mostRight = cur.left;
// 如果有左子树
if (mostRight != null) {
// 找当前节点左子树的最优解点
while (mostRight.right != null && mostRight.right != cur) {
mostRight = mostRight.right;
}
// 说明第一次遍历到cur节点
if (mostRight.right == null) {
mostRight.right = cur;
// 将上一个遍历的节点的左指针指向cur,这里之所以用左指针,是因为右指针在后面还有用,但是左指针没用了,所以暂时用左指针指向链表的下一个节点
if (pre != null) {
pre.left = cur;
}
// 更新pre
pre = cur;
cur = cur.left;
continue;
// 说明第二次遍历到cur节点
} else {
mostRight.right = null;
}
// 当前节点没有左子树,那么这个节点只会遍历一次
} else {
// 同样将这个节点加到链表结构中
if (pre != null) {
// 暂时使用节点左指针连接下一个节点
pre.left = cur;
}
pre = cur;
}
cur = cur.right;
}
// 遍历链表结构,用右指针取代左指针指向下一个节点,并将左指针指向null
cur = root;
TreeNode next = null;
while (cur != null) {
next = cur.left;
cur.right = next;
cur.left = null;
cur = next;
}
}
}
三、解题思路
利用Morris遍历实现空间复杂度O(1)的代码。
相关文章
- 115. distinct subsequence leetcode python
- [LeetCode] Find Minimum in Rotated Sorted Array II
- [LeetCode] Word Search
- LeetCode题解——700.二叉树搜索树中的搜索
- 106、【树与二叉树】leetcode ——501. 二叉搜索树中的众数:双指针法+哈希表法(C++版本)
- 91、【树与二叉树】leetcode ——559.n叉树的最大深度(递归DFS+迭代BFS)(C++版本)
- LeetCode Insert Interval
- 【LeetCode】32. Longest Valid Parentheses (2 solutions)
- 【leetcode】114: 二叉树展开为链表
- 【leetcode】111:二叉树的最小深度
- [LeetCode] 1145. Binary Tree Coloring Game 二叉树着色游戏
- [LeetCode] 968. Binary Tree Cameras 二叉树相机
- [LeetCode] 891. Sum of Subsequence Widths 子序列宽度之和
- [LeetCode] 889. Construct Binary Tree from Preorder and Postorder Traversal 由先序和后序遍历建立二叉树
- [LeetCode] 437. Path Sum III 二叉树的路径和之三
- [LeetCode] Minimum Moves to Equal Array Elements II 最少移动次数使数组元素相等之二
- [LeetCode] 81. Search in Rotated Sorted Array II 在旋转有序数组中搜索之二
- [LeetCode] Balanced Binary Tree 平衡二叉树
- leetcode 145. Binary Tree Postorder Traversal 二叉树的后序遍历 (中等)
- leetcode 101. Symmetric Tree 对称二叉树(简单)
- leetcode算法226.翻转二叉树