给你二叉树的根结点 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) {
dfs(root);
}
void dfs(TreeNode root) {
if (root == null)
return;
dfs(root.left);
dfs(root.right);
if (root.left != null) {
TreeNode pre = root.left;
while (pre.right != null)
pre = pre.right;
pre.right = root.right;
root.right = root.left;
root.left = null;
}
}
}
//右左根遍历,妙啊!
class Solution {
TreeNode st;
public void flatten(TreeNode root) {
dfs(root);
}
void dfs(TreeNode root) {
if (root == null)
return;
dfs(root.right);
dfs(root.left);
root.right = st;
root.left = null;
st = root;
}
}
//自下而上,一种类Morris遍历
class Solution {
public void flatten(TreeNode root) {
while (root != null) {
if (root.left != null) {
TreeNode pre = root.left;
while (pre.right != null)
pre = pre.right;
pre.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}