All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.amygdalum.util.graph.PreOrderTraversal Maven / Gradle / Ivy

The newest version!
package net.amygdalum.util.graph;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public abstract class PreOrderTraversal> implements Traversal {

	@Override
	public void traverse(GraphNode start) {
		Set> visited = new HashSet<>();

		Deque> ordered = new LinkedList<>();
		Deque> preOrdered = new LinkedList<>();

		ordered.push(start);

		while (!ordered.isEmpty()) {
			GraphNode node = ordered.peek();
			if (visited.contains(node)) {
				ordered.pop();
				continue;
			}
			visited.add(node);
			
			preOrdered.add(node);

			GraphNode[] successors = node.getSuccessors();
			for (int i = successors.length-1; i >= 0 ; i--) {
				if (visited.contains(successors[i])) {
					continue;
				}
				ordered.push(successors[i]);
			}
		}

		for (GraphNode node : preOrdered) {
			visitGraphNode(node);
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy