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

# Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

```
    1
   / \
  2   5
 / \   \
3   4   6
```

The flattened tree should look like:

```
1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
```

```java
class Solution {
    public TreeNode helper(TreeNode root) {
        if (root.left == null && root.right == null)
            return root;
        TreeNode lowestRight = null;
        if (root.left != null && root.right != null) {
            TreeNode leftLowest = helper(root.left);
            TreeNode rightLowest = helper(root.right);
            leftLowest.right = root.right;
            root.right = root.left;
            root.left = null;
            lowestRight = rightLowest;
        } else if (root.right != null) {
            lowestRight = helper(root.right);
        } else {
            lowestRight = helper(root.left);
            root.right = root.left;
            root.left = null;
        }
        return lowestRight;
    }

    public void flatten(TreeNode root) {
        if(root==null)
            return;
        helper(root);
    }
}
```
