---
# System prepended metadata

title: 114. Flatten Binary Tree to Linked List
tags: [' bt', tree]

---

---
link: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
tags: tree, bt
---

# 114. Flatten Binary Tree to Linked List

## Question
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
```

## Solution: Python
```python=
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def __init__(self):
        self.prev = None
        
    def flattenPost(self, node):
        """
        :type node: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        if node is None:
            return
        
        self.flatten(node.right)
        self.flatten(node.left)
    
        node.right = self.prev
        node.left = None
        self.prev = node
        
    
    def flattenPre(self, node):
        """
        :type node: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        if node is None:
            return
    
        _ = node.right
        
        print node.val, self.prev
        if self.prev is not None:
            self.prev.right = node
            self.prev.left = None
        self.prev = node
        
        self.flatten(node.left)
        self.flatten(_)
        
        return
        
        
    
    def flattenInorder(self, node):
        """
        :type node: TreeNode
        :rtype: None Do not return anything, modify root in-place instead.
        """
        if node is None:
            return None
    
        left = self.flatten(node.left)
        
        _ = node.right
        
        if left is not None:
            left.right = _
            node.right = node.left
            node.left = None
                
        right = self.flatten(_)
        
        return right or left or node
        
        
```

## Solution: Java
```java=        
```