1

I am new in tree like structures.I have write this kind of a tree.

How to iterate over a tree ? How to find all roots (i have a method for the main root but i want to find all roots which are inside the tree) in a tree ? What is the correct way to use a tree structure in java - every time write your one class or using TreeMap ?

TreeNode

public class TreeNode<T> {
private T value;
private boolean hasParent;
private ArrayList<TreeNode<T>> children;

public TreeNode(T value) {
    if (value == null) {
        throw new IllegalArgumentException("Cannot insert null value!");
    }
    this.value = value;
    this.children = new ArrayList<TreeNode<T>>();
}

public final T getValue() {
    return this.value;
}

public final void setValue(T value) {
    this.value = value;
}

public final int getChildrenCount() {
    return this.children.size();
}

public final void addChild(TreeNode<T> child) {
    if (child == null) {
        throw new IllegalArgumentException("Cannot insert null value!");
    }

    if (child.hasParent) {
        throw new IllegalArgumentException("The node already has a parent!");
    }

    child.hasParent = true;
    this.children.add(child);
}

public final TreeNode<T> getChild(int index) {
    return this.children.get(index);
}

Tree

public class Tree<T> {
TreeNode<T> root;

public Tree(T value) {
    if (value == null) {
        throw new IllegalArgumentException("Cannot insert null value!");
    }

    this.root = new TreeNode<T>(value);
}

public Tree(T value, Tree<T>... children) {
    this(value);
    for (Tree<T> child : children) {
        this.root.addChild(child.root);
    }
}

public final TreeNode<T> getRoot() {
    return this.root;
}

1 Answers1

0

Here i can use all inner roots and all nodes.

while (!stack.isEmpty()) {

         TreeNode<Integer> currentNode = stack.pop();
         for (int i = 0; i < currentNode.getChildrenCount(); i++) {
            TreeNode<Integer> childNode = currentNode.getChild(i);
            if (childNode == null) {
                System.out.println("Not a root.");
            } else {
                System.out.println(childNode.getValue());
                counter += childNode.getChildrenCount();
            }
        }

    }