diff --git a/src/Traverse.java b/src/Traverse.java index 7945513..22cfca6 100644 --- a/src/Traverse.java +++ b/src/Traverse.java @@ -28,6 +28,50 @@ 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 current) { + Set> visited = new HashSet<>(); + return sum(current, visited); + } + + public static int sum(Vertex current, Set> visited) { + if(current == null || visited.contains(current)) return 0; + visited.add(current); + int total = 0; + + total += current.data; + for(Vertexneighbor : current.neighbors) + { + int neighborSum = sum(neighbor, visited); + total += neighborSum; + } + return total; + + } + + + + public static void traverse(Vertex current) { + Set> visited = new HashSet<>(); + traverse(current, visited); + } + + public static void traverse(Vertex current, Set> visited) { + if(current == null || visited.contains(current)) return; + + System.out.println(current.data); + visited.add(current); + + for(Vertex neighbor : current.neighbors) { + traverse(neighbor, visited); + } } }