forked from RasPat1/practice-codewars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FunWithTrees.java
89 lines (73 loc) · 1.68 KB
/
FunWithTrees.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
import java.util.*;
public class FunWithTrees {
static ListNode flatten(TreeNode root) {
if (root == null) {
return null;
}
TreeSet<ListNode> set = new TreeSet<>(new SortedListNode());
flatten(root, set);
// iterate through the set
// set each element to connect to the next
ListNode previousNode = null;
for (ListNode ln : set) {
if (previousNode == null) {
previousNode = ln;
} else {
previousNode.next = ln;
previousNode = ln;
}
}
// make sure last element does't point to anything
set.last().next = null;
return set.first();
}
static void flatten(TreeNode root, TreeSet set) {
if (root != null) {
visit(root.value, set);
flatten(root.left, set);
flatten(root.right, set);
}
}
public static void visit(ListNode node, TreeSet set) {
while (node != null) {
set.add(node);
node = node.next;
}
}
static class SortedListNode implements Comparator<ListNode> {
@Override
public int compare(ListNode ln1, ListNode ln2) {
Integer i1 = new Integer(ln1.data);
Integer i2 = new Integer(ln2.data);
return i1.compareTo(i2);
}
}
}
/*
class TreeNode {
public TreeNode left;
public TreeNode right;
public ListNode value;
TreeNode(ListNode value, TreeNode left, TreeNode right) {
this.value = value;
this.left = left;
this.right = right;
}
TreeNode(ListNode value) {
this(value, null, null);
}
}
*/
/*
class ListNode {
public int data;
public ListNode next;
ListNode(int data, ListNode next) {
this.data = data;
this.next = next;
}
ListNode(int data) {
this(data, null);
}
}
*/