给你二叉树的根结点 root ,请你将它展开为一个单链表:
示例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]
const flatten = (root) => {
if(!root) return ;
flatten(root.left); // 递归 root 的 左子树 和 右子树
flatten(root.right);
// 暂存叶子结点的左子树和右子树
let left = root.left;
let right = root.right;
root.left = null; // 将左子树置为 null
root.right = left; // 将右子树置为 左子树
while(root.right !== null) { // 遍历右子树,直至找到右子树的叶子结点
root = root.right;
}
root.right = right // 将刚才暂存的 右子树 替换上去
return root
}