Search code examples
javaparent-childtreemap

Obtain ALL children of a given node in TreeMap


I am using java 8. I found out there is an object TreeMap pre-implimented in java. I am wondering how I can obtain children nodes of a certain node.

I have written the following recursive code, but it does not work.

static TreeMap<String,SimpleNode> tree = new TreeMap<String,SimpleNode>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    Stack nodesToDelete = new Stack();
    nodesToDelete.add(parentNode.getId());
    SimpleNode children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));


        findChildrenToDelete(children.get(i));

     return  nodesToDelete;  
} 

I mean the method should provide a stack of children nodes

I saw the methods of the class and i didn't find a straight forward solution.


Solution

  • The reason why it does not work is because you don't do anything with the result of the recursive call. You have to append these children to the result.

    static TreeMap<String,ArrayList<SimpleNode>> tree = new TreeMap<String,ArrayList<SimpleNode>>();
    
    public Stack findChildrenToDelete(SimpleNode parentNode){
        Stack nodesToDelete = new Stack();
        nodesToDelete.add(parentNode.getId());
        ArrayList<SimpleNode> children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));
    
        for(int i=0;i<children.size();i++){
            // add recursive children to the result
            nodesToDelete.addAll(findChildrenToDelete(children.get(i)));
        }
        return nodesToDelete;  
    }

    Alternatively you can pass a reference to the collection you are building and add to the collection during the recursion:

    static TreeMap<String,ArrayList<SimpleNode>> tree = new TreeMap<String,ArrayList<SimpleNode>>();
    
    public Stack findChildrenToDelete(SimpleNode parentNode){
        return findChildrenToDelete(parentNode,new Stack());
    }
    public Stack findChildrenToDelete(SimpleNode parentNode, Stack nodesToDelete){
        nodesToDelete.add(parentNode.getId());
        ArrayList<SimpleNode> children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));
    
        for(int i=0;i<children.size();i++){
            // pass a reference to the collection recursively
            findChildrenToDelete(children.get(i),nodesToDelete);
        }
        return nodesToDelete;  
    }