From 3a1f9e4afaa1068c76bf31e717f34aaf1ff91dfd Mon Sep 17 00:00:00 2001 From: Kimberly Mageary Date: Fri, 7 Mar 2025 22:16:10 -0800 Subject: [PATCH] Finished the excersize --- src/Traverse.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/Traverse.java b/src/Traverse.java index 7945513..b3a78cc 100644 --- a/src/Traverse.java +++ b/src/Traverse.java @@ -28,6 +28,29 @@ 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)); + + Set> visited = new HashSet<>(); + dfs(v67, visited); + dfs(v91, visited); + } + + public static void dfs(Vertex vertex, Set> visited){ + // if null return + if(vertex == null) return; + if(visited.contains(vertex)) return; + + //print out node + visited.add(vertex); + System.out.println(vertex.data); + + // if children of nodes are null return + if(vertex.neighbors == null) return; + + // make a list of children and loop through + // recursively call method for each child + for(Vertex neighbor : vertex.neighbors){ + dfs(neighbor, visited); + } } }