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

com.link_intersystems.graph.tree.DepthFirstBottomUpTreeModelIterable Maven / Gradle / Ivy

Go to download

There is a newer version: 1.9.7
Show newest version
package com.link_intersystems.graph.tree;

import java.util.*;
import java.util.stream.Stream;

/**
 * Iterates through a tree model by depth first strategy, but returns the elements in reverse order of the branches.
 * 

* Assume the following tree structure. The number show the iteration order. * *

 *
 *          +-(2)--(1)
 *          |
 *      (7)-+-(3)
 *          |
 *          |     +-(4)
 *          |     |
 *          +-(6)-+
 *                |
 *                +-(5)
 * 
*

* You can {@link #setLeavesOnly(boolean)} to true and it will only iterate the leaves: 1, 4, 5. * * @author René Link {@literal } */ public class DepthFirstBottomUpTreeModelIterable extends AbstractTreeModelIterable { private boolean leavesOnly; public DepthFirstBottomUpTreeModelIterable(TreeModel treeModel, T rootElement) { super(treeModel, rootElement); } public void setLeavesOnly(boolean leavesOnly) { this.leavesOnly = leavesOnly; } @Override protected Iterator createIterator(TreeModel treeModel, T rootElement) { Stack stack = new Stack<>(); stack.push(rootElement); Set childrenResolved = Collections.newSetFromMap(new IdentityHashMap<>()); Map isLeaf = new IdentityHashMap<>(); return new Iterator() { @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } while (true) { T head = stack.peek(); if (childrenResolved.contains(head)) { break; } Stream children = treeModel.getChildren(head); int headIndex = stack.size(); children.forEach(c -> stack.add(headIndex, c)); childrenResolved.add(head); boolean stackNotModified = headIndex == stack.size(); isLeaf.put(head, stackNotModified); if (stackNotModified) { break; } else { if (leavesOnly) stack.remove(headIndex - 1); } } T next = stack.pop(); return next; } }; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy