Java generic tree traversal with node filtering

tree traversal examples
tree traversal calculator
binary tree traversal program in c
binary search tree traversal inorder, preorder postorder example
pre-order traversal binary tree java
in order traversal of binary tree java
post order traversal binary tree java
inorder traversal for general tree

I have a generic tree structure. I need an algorithm to traverse it, and remove some leafs if they are not contained in a given list. If all the leafs are removed from a subtree, then remove the whole subtree too.

Example tree:

       / |  \
      1  2   3
    /  \ |  / \
   4   5 6  7  8

Leafs to keep: {4, 6}

Result tree:

       / | 
      1  2 
    /    | 
   4     6  

The input data structure is contained in a HashMap where the key is the parent id of the nodes, and the value is a List of the Nodes directly under the parent (but not recursively all children). The parent id of the root node is empty string.

Map<String, List<Node>> nodes;

class Node {
    private String id;
    //other members
    //getters, setters

I suppose, some kind of recursive DFS traversal algorithm should work, but I couldn't find it out, how.

I suggest you to try the following approach:

The method boolean removeRecursively(String id, Set<String> leavesToKeep) will traverse from the node with the given id down to this branch leaves.

First we check whether the curent node is a leaf or not. If the leaf is not in the leavesToKeep set, we remove it and return true, otherwise return false. This is a base case of our recursion.

If the node is not a leaf, then we do something like this:

children.removeIf(n -> removeRecursively(, leavesToKeep));

removeIf is a convenient Java 8 method to remove all of the elements that satisfy the given predicate. This means that the child will be removed from the list only if all of its children are removed too. Therefore, we should make removeRecursively return true if after the children.removeIf call the children list is empty:

if (children.isEmpty()) {
    return true;
} else return false;

Full method may look like this:

public static boolean removeRecursively(Map<String, List<Node>> tree, String id, Set<String> leavesToKeep) {
    List<Node> children = tree.get(id);
    if (children == null || children.isEmpty()) {
        if (!leavesToKeep.contains(id)) {
            return true;
        } else return false;
    children.removeIf(n -> removeRecursively(tree,, leavesToKeep));
    if (children.isEmpty()) {
        return true;
    } else return false;

where tree is the map you described, id is the start node id, leavesToKeep is a set of ids to keep.

algorithm - Java generic tree traversal with node filtering, I have a generic tree structure. I need an algorithm to traverse it, and remove some leafs if they are not contained in a given list. If all the leafs are removed from a  General Tree (Each node can have arbitrary number of children) Level Order Traversal; Breadth First Search without using Queue; Minimum time to burn a Tree starting from a Leaf node; Print all nodes at distance K from given node: Iterative Approach; Check if given words are present in a string; Level order traversal in spiral form | Using Deque

Computational Science, This is based on a filtering mechanism introduced into the JVM agent, which to derive a more specific event class from a more general one. event classes in the tree, by doing a tree traversal starting with the tree's root, which matches all events. At each traversed node, the filters associated with that node are evaluated. Please not your code does not compile. You have a few challenges here - A. Define Node as Generic - public class Node<T> { private T value; // here goes the rest of your code }

With interface Tree:

public static interface Tree<T> {
    public T getValue();

    public List<Tree<T>> children();

    public default boolean isLeaf() {
        return children().isEmpty();

    public default boolean removeDeadBranches(Predicate<T> testLiveLeaf) {
        if (isLeaf()) {
            return testLiveLeaf.test(getValue());
        boolean remainLife = false;
        for (Iterator<Tree<T>> it = children().iterator(); it.hasNext();) {
            if ( {
                remainLife = true;
            } else {
        return remainLife;

JavaScript: Trees - Mahendra Choudhary, One of the tree traversal methods (graph in general). The strategy Filtering leaves the leaf nodes and the subsequent filtering by the template. Minimum time to burn a Tree starting from a Leaf node; Print all nodes at distance K from given node: Iterative Approach; Check if given words are present in a string; Level order traversal in spiral form | Using Deque; Inorder traversal of an N-ary Tree; Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class FilterTreeNode {
    private Logger logger = LoggerFactory.getLogger(FilterTreeNode.class);
    private TreeNode node0;
    private List<String> targetNode = Lists.newArrayList("B1","D1");

    public void init(){
        node0 = TreeNode.builder().nodeCode("0").nodeName("A").build();
        TreeNode node1 = TreeNode.builder().nodeCode("1").nodeName("B").build();
        TreeNode node2 = TreeNode.builder().nodeCode("2").nodeName("C").build();
        TreeNode node3 = TreeNode.builder().nodeCode("3").nodeName("D").build();

        TreeNode node4 = TreeNode.builder().nodeCode("4").nodeName("B1").build();
        TreeNode node5 = TreeNode.builder().nodeCode("5").nodeName("B2").build();
        TreeNode node6 = TreeNode.builder().nodeCode("6").nodeName("C1").build();
        TreeNode node7 = TreeNode.builder().nodeCode("7").nodeName("D1").build();
        TreeNode node8 = TreeNode.builder().nodeCode("8").nodeName("D2").build();



    public void filterTest(){"before filter node0: {}",node0);
        List<TreeNode> retNodes = filterNode(node0);
        if (retNodes.size() >0){
        }"after filter node0: {}",node0);

    private List<TreeNode> filterNode(TreeNode treeNode){

        List<TreeNode> nodes = treeNode.getChildren();
        List<TreeNode> newNodes = Lists.newArrayList();
        List<TreeNode> tagNodes = Lists.newArrayList();

        for(TreeNode node : nodes){
            if (targetNode.contains(node.getNodeName())){
            if (node.getChildren() != null && node.getChildren().size() >0){
                List<TreeNode> retNodes = filterNode(node);
                if (retNodes.size()>0){
                }else {
        return newNodes;

XML Primer Plus, 14 for an example of a NodeFilter that actually filters. for now we'll set the NodeFilter to null in the Java example, and a generic filter in the Perl example. that references a whole tree of elements, the Nodelterator will see each element. DocumentTraversal traversal = Chapter 4 • ADVANCED DOM TECHNIQUES 151  Stack Overflow Public So i want to know that in java do we have anything like jqueryfiletree which takes Java generic tree traversal with node filtering.

Tree traversal, Implement a binary tree where each node carries an integer, and implement: pre-​order 41 Java. 41.1 Java: Procedural; 41.2 Java: Object Oriented takeNone.​inputRangeObject; return [t.left, t.right] .filter!(t => t != null) .map! In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used. Example: Inorder traversal for the above-given figure is 4 2 5 1 3. Preorder Traversal : Algorithm Preorder(tree) 1.

Tree traversal, Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree, but  Simple Generic N-ary Tree implementation in Java Utility methods: To check if a node exists in the tree. To find the total number of nodes in the tree; To find the total number of descendants of any node in the tree. To get all the paths from the root to all the leaves as a List. To get all longest path from the root to any leaf.

Red–black tree, In computer science, a red–black tree is a kind of self-balancing binary search tree. Each node Red–black trees, like all binary search trees, allow efficient in-​order traversal (that is: in the order Left–Root–Right) of their elements. In the version 8 of Java, the HashMap has been modified such that instead of using a  (In case you want to avoid the lengthy explanation, all I am looking for is a level order traversal for a generic-tree(n-ary tree) in java. The code supplied works and needs the level order display function. Looked around for an hour but couldnt find reference to generic n-ary trees.