在Java树结构中迭代和查找根

时间:2015-11-04 10:18:17

标签: java tree

我是树状结构的新手。我写过这种树。

如何迭代树? 如何在树中找到所有根(我有一个主根的方法,但我想找到树内的所有根)? 在java中使用树结构的正确方法是什么 - 每次编写一个类或使用TreeMap?

树节点

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);
}

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 个答案:

答案 0 :(得分:0)

在这里,我可以使用所有内部根和所有节点。

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();
            }
        }

    }