> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/tree/114.-flatten-binary-tree-to-linked-list.md).

# 114. Flatten Binary Tree to Linked List

![](/files/-MlLFREoeWoCKogRw6Bi)

![](/files/-MlLFUjm7klJLAjV0phb)

time: O(n)

space: O(n), which is occupied by the recursion stack

```java
class Solution {
    public void flatten(TreeNode root) {
        flattenImpl(root);
    }
    private TreeNode flattenImpl(TreeNode root) {
        if (root == null) {
            return null;
        }
        
        TreeNode leftLast = flattenImpl(root.left);
        TreeNode rightLast = flattenImpl(root.right);
        
        if (leftLast != null) {
            leftLast.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        if (rightLast != null) {
            return rightLast;
        } else if (leftLast != null) {
            return leftLast;
        }
        return root;
    }
}

/*
root left right

2 - 3 - 4
leftlast = 3
rightlast = 4


return rightLast // 4

*/
```

space O(1), next time...
