diff --git a/src/Traverse.java b/src/Traverse.java index 7945513..e4f170b 100644 --- a/src/Traverse.java +++ b/src/Traverse.java @@ -28,6 +28,40 @@ 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)); + + printGraph(v3); + System.out.println("sum:" + sum(v3)); } -} + public static int sum(Vertex current){ + Set> visited = new HashSet<>(); + return sum(current, visited); + } + public static int sum(Vertex vertex, Set> visited){ + if(vertex == null || visited.contains(vertex)) return 0; + int total = 0; + total+= vertex.data; + visited.add(vertex); + for(Vertex neighbor : vertex.neighbors){ + total += sum(neighbor, visited); + } + return total; + } + + + public static void printGraph(Vertex vertex){ + Set> visited = new HashSet<>(); + printGraph(vertex, visited); + } + public static void printGraph(Vertex vertex, Set> visited){ + if(vertex == null || visited.contains(vertex)) return; + + System.out.println(vertex.data); + visited.add(vertex); + for(Vertex neighbor : vertex.neighbors){ + printGraph(neighbor, visited); + } + + + } +} \ No newline at end of file