Search code examples
recursiontree

traversing a object tree, find an item and return the object


prerequisites: Each branch in the tree can have any number of further branches.

I tried to traverse the tree usinge a recursion. When the object is found it is returned to the higher-level instance. At the beginning of the code treeItemfound has to be initialized, after returning the found object it is overwritten with null. So the result of the function, (item found or not) everytime is null.

here my code:

public static TreeItem getTreeItem2(TreeItem treeItem, Integer itemId) {

    TreeItem<Category> treeItemfound = null;
    
    System.out.println(treeItem + " :ich bin ein Element...   itemId=" + itemId);
    ObservableList<TreeItem<Category>> currentTreeList = treeItem.getChildren();

    for (int i = 0; i < currentTreeList.size(); i++) {
        treeItemfound = getTreeItem2(currentTreeList.get(i), itemId);
    }
    

    if (treeItem.getValue().getCat_Ident() == itemId) {
        treeItemfound = treeItem;
        System.out.println(treeItemfound + "   ***treeItem found***");
        System.out.println("===================================================");
    }
    
    

    
    System.out.println(treeItem+"###########################################");
    System.out.println(treeItemfound);

    return treeItemfound;

}

Solution

  • When from a recursive call you get a value for treeItemfound, you should inspect that value. If it is not null, there is no reason to make any further iterations of the loop and make any other recursive call. You should exit immediately with the same non-null value:

        for (int i = 0; i < currentTreeList.size(); i++) {
            treeItemfound = getTreeItem2(currentTreeList.get(i), itemId);
            if (treeItemfound != null) return treeItemfound; // <---
        } 
    

    Not a problem, but why not first check whether the current node has the searched value -- before making any recursive calls? It that matches, you can immediately return the current node without making any recursive calls, saving a potentially large quantity of "work".