Skip to content

Commit 8839319

Browse files
committed
Added 2 solutions
1 parent d1f5a7b commit 8839319

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
public int val;
5+
public List<Node> children;
6+
7+
public Node() {}
8+
9+
public Node(int _val,List<Node> _children) {
10+
val = _val;
11+
children = _children;
12+
}
13+
};
14+
*/
15+
class Codec {
16+
17+
// Encodes a tree to a single string.
18+
StringBuilder sb;
19+
public String serialize(Node root) {
20+
if (root == null) {
21+
return "";
22+
}
23+
24+
sb = new StringBuilder();
25+
serializeHelper(root);
26+
27+
return sb.toString().substring(0, sb.length() - 1);
28+
}
29+
30+
private void serializeHelper(Node root) {
31+
if (root == null) {
32+
return;
33+
}
34+
35+
sb.append(root.val).append(",").append(root.children.size()).append(",");
36+
for (Node child : root.children) {
37+
serializeHelper(child);
38+
}
39+
}
40+
41+
// Decodes your encoded data to tree.
42+
public Node deserialize(String data) {
43+
if (data == null || data.length() == 0) {
44+
return null;
45+
}
46+
47+
Queue<String> queue = new LinkedList<>();
48+
queue.addAll(Arrays.asList(data.split(",")));
49+
50+
return deserializeHelper(queue);
51+
}
52+
53+
private Node deserializeHelper(Queue<String> queue) {
54+
Node root = new Node();
55+
root.val = Integer.parseInt(queue.remove());
56+
int size = Integer.parseInt(queue.remove());
57+
58+
root.children = new ArrayList<>(size);
59+
60+
for (int i = 0; i < size; i++) {
61+
root.children.add(deserializeHelper(queue));
62+
}
63+
64+
return root;
65+
}
66+
}
67+
68+
// Your Codec object will be instantiated and called as such:
69+
// Codec codec = new Codec();
70+
// codec.deserialize(codec.serialize(root));

Medium/Reconstruct Itinerary.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public List<String> findItinerary(List<List<String>> tickets) {
3+
Map<String, PriorityQueue<String>> map = new HashMap<>();
4+
for (List<String> ticket : tickets) {
5+
map.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1));
6+
}
7+
8+
List<String> route = new ArrayList<>();
9+
Stack<String> stack = new Stack<>();
10+
11+
stack.push("JFK");
12+
13+
while (!stack.isEmpty()) {
14+
while (map.containsKey(stack.peek()) && !map.get(stack.peek()).isEmpty()) {
15+
stack.push(map.get(stack.peek()).poll());
16+
}
17+
18+
route.add(stack.pop());
19+
}
20+
21+
Collections.reverse(route);
22+
23+
return route;
24+
}
25+
}

0 commit comments

Comments
 (0)