# Flatten Binary Tree to Linked List

https://leetcode.com/problems/flatten-binary-tree-to-linked-list

## Preorder traversal

Create a linked list from the nodes visited by preorder travelling.

### Source code *Read on Github*

```
1 /**
2 * Definition for binary tree
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode(int x) { val = x; }
8 * }
9 */
10 public class Solution {
11
12 TreeNode prev;
13
14 void preorder(TreeNode root){
15
16 if(root == null) return;
17
18 TreeNode left = root.left;
19 TreeNode right = root.right;
20
21 // root
22 if(prev != null){
23 prev.right = root;
24 prev.left = null;
25 }
26
27 prev = root;
28
29 preorder(left);
30 preorder(right);
31 }
32
33
34 public void flatten(TreeNode root) {
35 // Note: The Solution object is instantiated only once and is reused by each test case.
36 prev = null;
37 preorder(root);
38 }
39 }
```