-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFlattenBinaryTreeToLinkedList.java
More file actions
68 lines (60 loc) · 1.19 KB
/
FlattenBinaryTreeToLinkedList.java
File metadata and controls
68 lines (60 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package leetcode;
import java.util.LinkedList;
/**
* @author eko
*
* 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
*
*/
public class FlattenBinaryTreeToLinkedList {
public static void main(String[] args) {
TreeNode node = new TreeNode(1);
node.left = new TreeNode(2);
node.right = new TreeNode(3);
new FlattenBinaryTreeToLinkedList().flatten(node);
while(node != null) {
System.out.println(node.val);
node = node.right;
}
}
private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null) {
return;
}
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}