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
42 changes: 42 additions & 0 deletions src/Traverse.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.List;
import java.util.Set;


public class Traverse {
public static void main(String[] args) {
// See below site for visualization of this graph
Expand All @@ -28,6 +29,47 @@ 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));

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

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

public static int sum(Vertex<Integer> current){
Set<Vertex<Integer>> visited = new HashSet<>();
return sum(current, visited);
}

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);
total += neighborSum;
}

return total;
}

public static <T> void traverse(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){
traverse(neighbor, visited);
}

}

}