forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlattenBinaryTree.java
94 lines (84 loc) · 2.24 KB
/
FlattenBinaryTree.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package tree;
/**
* Created by gouthamvidyapradhan on 04/07/2017.
* Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Solution: Do a pre-order traversal and maintain head and tail of a linked list at each recursive step.
i. Join the current node to the head of the left sub-list to form the current node as the new head.
ii. Join the tail of the left sub-list to the head of the right sub-list.
iii. Mark the left of the current node as null
*/
public class FlattenBinaryTree {
/**
* Class to keep track of head and tail
*/
private class LinkNode{
TreeNode head;
TreeNode tail;
LinkNode(TreeNode head, TreeNode tail){
this.head = head;
this.tail = tail;
}
}
public static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static void main(String[] args) throws Exception{
TreeNode root = new TreeNode(3);
root.left = new TreeNode(2);
root.right = new TreeNode(1);
new FlattenBinaryTree().flatten(root);
System.out.print(root.val+ " ");
System.out.print(root.right.val + " ");
System.out.print(root.right.right.val);
}
public void flatten(TreeNode root) {
preOrder(root);
}
private LinkNode preOrder(TreeNode node){
if(node == null) return null;
LinkNode left = preOrder(node.left);
LinkNode right = preOrder(node.right);
LinkNode lNode;
if(left == null && right == null){
lNode = new LinkNode(node, node);
}
else if(left == null){
node.right = right.head;
lNode = new LinkNode(node, right.tail);
}
else if(right == null){
node.right = left.head;
lNode = new LinkNode(node, left.tail);
}
else {
node.right = left.head;
left.tail.right = right.head;
lNode = new LinkNode(node, right.tail);
}
node.left = null;
return lNode;
}
}