-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenTree.java
More file actions
63 lines (54 loc) · 1.79 KB
/
FlattenTree.java
File metadata and controls
63 lines (54 loc) · 1.79 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
package Trees;
/**
* Morris Traversal, one of the craziest trick!
*/
public class FlattenTree {
/* In this approach we are using recursion to flatten a tree.
* It causes us to use O(H) extra space in terms of recursion calls.
* We have to store values in preorder format.
* Time Complexity of this approach is O(N).
*/
public static void flatten(Node root) {
if (root == null) return;
Node leftTree = root.left;
Node rightTree = root.right;
root.left = null;
flatten(leftTree);
flatten(rightTree);
root.right = leftTree;
Node temp = leftTree;
while (temp != null && temp.right != null) {
temp = temp.right;
}
if (temp != null) temp.right = rightTree;
else root.right = rightTree;
}
/*
* This approach is known as Morris Traversal, it uses O(1) extra space.
* It is similar to a linked list being reversed we use two pointers.
* */
public static void flattenMorris(Node root) {
Node curr = root;
while (curr != null) {
if (curr.left != null) {
Node predecessor = curr.left;
while (predecessor.right != null) {
predecessor = predecessor.right;
}
predecessor.right = curr.right;
curr.right = curr.left;
curr.left = null;
}
curr = curr.right;
}
}
public static void main(String[] args) {
String[] arr = {"1", "2", "3", "4", "5", "6", "7"};
Node root = ConstructTree.construct(arr);
flattenMorris(root);
while (root != null) {
if (root.left != null) System.err.println("Test Failed");
root = root.right;
}
}
}