Search code examples
javaif-statementwhile-loopjtreetreenode

Java TreeNode while statement


I am working on code for a java TreeNode. I will like to do a while statement to loop through from the root of the tree to all subsequent nodes and update numbers. I can do this with an if statement but this only loops through the first nodes and ends there.

    if
    (node.getChildCount() > 0)
    {
        updatenumbers(node);
    }

I tried this while statement but this causes an abrupt stop of the program and does not update the tree, no errors or exceptions thrown. I'm not sure what the issue is.

    while
    (node.getChildCount() > 0)
    {
        updatenumbers( 0, node);
    }

This is the code for updatenumbers

 private void updatenumbers(int _index, MutableTreeNode _node) {
    int count = _node.getChildCount;
    for (int i = _index; i < count ; i++){
        node.setindex(i);
    }

Solution

  • Say you have the root node:

    MutableTreeNode rootNode = //whatever
    

    Then you can use an ArrayList as a queue like object to do a while loop over the tree.

    ArrayList<MutableTreeNode> queue = new ArrayList<MutableTreeNode>();
    queue.add(rootNode)
    while(queue.size() > 0){
        MutableTreeNode tempNode = queue.get(0);//access first element only
        updatenumbers(tempNode);  //update children of just this single node
        queue.remove(0);//remove from queue
    
        //now add the children of tempNode
        queue.add(tempNode.left);
        queue.add(tempNode.right);
    }
    

    In this example, I assume it's a binary search tree. You may want adjust the adding of children part based on what the tree actually is.

    Now for this method updatenumbers. You don't need to pass the starting index if it's always going to be 0. What your issue here is that you're setting the index of the current node and none of the children. You want to get the child from the node (ex. via custom method getChild(i)).

    private void updatenumbers(MutableTreeNode node) {
        int count = node.getChildCount;
        for (int i = 0; i < count ; i++){
            node.getChild(i).setindex(i);//you need a getChild method or something similar
    }
    

    Update: Since it was just revealed you are using JTree, these two sources for JTree that may help: