一、题目
1、题目描述
给你二叉树的根结点 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]
2、基础框架
- C++版本给出的基础框架如下:
3、原题链接
https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/
二、解题报告
1、思路分析
(
1
)
(1)
(1)如果左子树存在,将左子树放在右子树位置,右子树放在原左子树最右节点右侧。
(
2
)
(2)
(2)依次遍历右子树,重复执行(1)操作
2、时间复杂度
时间复杂度O(n),空间复杂度O(1)
3、代码详解
class Solution {
public void flatten(TreeNode root) {
while(root != null) {
if (root.left == null){
root = root.right;
} else {
TreeNode pre = root.left;
while (pre.right != null) {
pre = pre.right;
}
TreeNode r = root.right;
root.right = root.left;
root.left = null;
pre.right = r;
root = root.right;
}
}
}
}