题目描述:
    image.png
    image.png
    解析:可以发现展开的顺序其实就是二叉树的先序遍历。
    我们需要两步完成这道题。

    1. 将左子树插入到右子树的地方
    2. 将原来的右子树接到左子树的最右边节点
    3. 考虑新的右子树的根节点,一直重复上边的过程,直到新的右子树为 null

      整个流程如下:
      1
      / \
      2 5
      / \ \
      3 4 6

    //将 1 的左子树插入到右子树的地方
    1
    \
    2 5
    / \ \
    3 4 6
    //将原来的右子树接到左子树的最右边节点
    1
    \
    2
    / \
    3 4
    \
    5
    \
    6

    //将 2 的左子树插入到右子树的地方
    1
    \
    2
    \
    3 4
    \
    5
    \
    6

    //将原来的右子树接到左子树的最右边节点
    1
    \
    2
    \
    3
    \
    4
    \
    5
    \
    6

    ……

    1. public void flatten(TreeNode root) {
    2. while (root != null) {
    3. //左子树为 null,直接考虑下一个节点
    4. if (root.left == null) {
    5. root = root.right;
    6. } else {
    7. // 找左子树最右边的节点
    8. TreeNode pre = root.left;
    9. while (pre.right != null) {
    10. pre = pre.right;
    11. }
    12. //将原来的右子树接到左子树的最右边节点
    13. pre.right = root.right;
    14. // 将左子树插入到右子树的地方
    15. root.right = root.left;
    16. root.left = null;
    17. // 考虑下一个节点
    18. root = root.right;
    19. }
    20. }
    21. }