给你二叉树的根结点 root ,请你将它展开为一个单链表:

    展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
    展开后的单链表应该与二叉树 先序遍历 顺序相同。

    示例 1:
    image.png
    输入: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]

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {void} Do not return anything, modify root in-place instead.
    12. */
    13. var flatten = function (root) {
    14. if (!root) return;
    15. // 递归拉平
    16. flatten(root.left);
    17. flatten(root.right);
    18. // 左右子树已经被拉平
    19. let left = root.left;
    20. let right = root.right;
    21. // 将做子树作为右子树
    22. root.left = null;
    23. root.right = left;
    24. let p = root;
    25. while (p.right !== null) {
    26. p = p.right
    27. }
    28. p.right = right
    29. };

    image.png