# LeetCode – Reconstruct Itinerary (Java)

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Analysis

This is an application of Hierholzerās algorithm to find a Eulerian path.

PriorityQueue should be used instead of TreeSet, because there are duplicate entries.

Java Solution

 public class Solution{ HashMap> map = new HashMap>(); LinkedList result = new LinkedList();   public List findItinerary(String[][] tickets) { for (String[] ticket : tickets) { if (!map.containsKey(ticket[0])) { PriorityQueue q = new PriorityQueue(); map.put(ticket[0], q); } map.get(ticket[0]).offer(ticket[1]); }   dfs("JFK"); return result; }   public void dfs(String s) { PriorityQueue q = map.get(s);   while (q != null && !q.isEmpty()) { dfs(q.poll()); }   result.addFirst(s); } }
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>