NielsVE
NielsVE

Reputation: 3

Filling a tree bottom up

Basically what I need to do is form a tree-structure from an unsorted list with objects. This tree needs to be filled based on the parentId-attribute of the objects in the list. So if an object in the list has parentid=0, it is the root. If it has parentid=1 , then it is the child of the object with id =1. Under 'Filling the tree' is the problem. Now it is statically filled but I need a dynamic way to fill the tree. Hopefully someone can give me some advice. I have abstracted my problem and made the following code:

public class Node {
   private int id,parentid;
    private String text;

    public int getParentid() {
        return parentid;
    }

    public void setParentid(int parentid) {
        this.parentid = parentid;
    }

    Node(int id , String s,int pid){
        setId(id);
        setParentid(pid);
        setText(s);
    }

    public int getNummer() {
        return id;
    }

    public void setId(int nummer) {
        this.id = nummer;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;

public class NodeTreeSample {

    public static void main(String args[]) {

        JFrame frame = new JFrame("Tree");

        //The unsorted list with the objects
        Collection<Node> treeList = new ArrayList<Node>();
        treeList.add(new Node(1,"Rootnode",0));
        treeList.add(new Node(2,"Child of node with id 1",1));
        treeList.add(new Node(3, "Child of node with id 1", 1));
        treeList.add(new Node(4, "Child of node with id 2", 2));
        treeList.add(new Node(5, "Child of node with id 2", 2));

        DefaultMutableTreeNode root=new DefaultMutableTreeNode("Root");

        //Filling the tree
        for(Node n:treeList){
            if(n.getParentid()==0){
               root = new DefaultMutableTreeNode(n.getText());
            }
            if(n.getParentid()==1){
                root.add(new DefaultMutableTreeNode(n.getText()));
            }
            if(n.getParentid()==2){

            }
        }
        JTree tree = new JTree(root);
        JScrollPane scrollPane = new JScrollPane(tree);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    }
}

Upvotes: 0

Views: 1978

Answers (1)

Cybercartel
Cybercartel

Reputation: 12592

This isn't a binary tree or a very complicated tree and such you don't need a "dynamic solution" and I guess you don't mean dynamic programming? Anyway what you want is a depth-first search of the tree to insert a new node because this isn't a really complicated tree where you have to split a node.

Upvotes: 1

Related Questions