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