Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/Traverse.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,49 @@ public static void main(String[] args) {
v45.neighbors = new ArrayList<>(List.of(v23));
v23.neighbors = new ArrayList<>(List.of());
v67.neighbors = new ArrayList<>(List.of(v91));

//traverse(v3);
int result = sum(v45);
System.out.println(result);
}

public static int sum(Vertex<Integer> current) {
Set<Vertex<Integer>> myVisited = new HashSet<>();

return sum(current, myVisited);
}

public static int sum(Vertex<Integer> current, Set<Vertex<Integer>> visited) {
if (current == null || visited.contains(current)) return 0;

visited.add(current);

int total = 0;
total += current.data;

for (Vertex<Integer> neighbor : current.neighbors) {
int neighborSum = sum(neighbor, visited); // dont forget to do something with the returned result of our recursive call
total += neighborSum;
}

return total;
}

public static <T> void traverse(Vertex<T> current) {
Set<Vertex<T>> myVisited = new HashSet<>();
traverseHelper(current, myVisited);
}

// Core of our algorithm: THE most important to know for technical interviews
// - expects us to understand very thoroughly; as core as using for loop to go thru array
public static <T> void traverseHelper(Vertex<T> current, Set<Vertex<T>> visited) {
if (current == null || visited.contains(current)) return;

System.out.println(current.data);
visited.add(current);

for(Vertex<T> neighbor : current.neighbors) {
traverseHelper(neighbor, visited);
}
}
}