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.


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<String, PriorityQueue<String>> map = new HashMap<String, PriorityQueue<String>>();
	LinkedList<String> result = new LinkedList<String>();
	public List<String> findItinerary(String[][] tickets) {
		for (String[] ticket : tickets) {
			if (!map.containsKey(ticket[0])) {
				PriorityQueue<String> q = new PriorityQueue<String>();
				map.put(ticket[0], q);
		return result;
	public void dfs(String s) {
		PriorityQueue<String> q = map.get(s);
		while (q != null && !q.isEmpty()) {
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Pavan

    Isn’t this a way of doing? topological sort.