From 242903848375865eee4d4b8afe91b63e910dfd11 Mon Sep 17 00:00:00 2001 From: mlarsen <174657206+mlarsen-source@users.noreply.github.com> Date: Tue, 20 May 2025 11:41:04 -0700 Subject: [PATCH] In-class Livecode --- src/Traverse.java | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) 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); + } } }