【问题标题】:Creating a tree data structure in java?在java中创建树数据结构?
【发布时间】:2013-12-20 04:54:24
【问题描述】:

我正在尝试在 java 中创建一个树数据结构,其中每个父节点只能有三个子节点,但是在节点至少有一个子节点但少于3 个子节点。我不确定是否应该使用 Iterator 来遍历我所在的当前节点的节点列表。我尝试使用每次调用add() 方法时都会递增的变量。 这是我的代码: 节点类:

public class Node {

    int keyValue;
    int nodeLabel;
    ArrayList<Node> nodeChildren;

    private static int count;

    Node(int _keyValue)
    {
        this.nodeLabel = count;
        this.keyValue = _keyValue;
        this.count++;
        nodeChildren = new ArrayList<Node>();
    }

    public String toString()
    {
        return "Node " + nodeLabel + " has the key " + keyValue;
    }

}

树类:add() 方法

Node rootNode;
    int incrementor = 0;

    public void addNode(int nodeKey)
    {
        Node newNode = new Node(nodeKey);

        if (rootNode == null)
        {
            rootNode = newNode;
        }
        else if (rootNode.nodeChildren.isEmpty())
        {

            rootNode.nodeChildren.add(newNode);
        }
        else if (!rootNode.nodeChildren.isEmpty())
        {
            Node currentNode = rootNode;
            Node parentNode;
            incrementor = 0;

            while (currentNode.nodeChildren.size() < 3)
            {
                //currentNode.nodeChildren.add(newNode); 
                if (currentNode.nodeChildren.size() == 3)
                {
                    parentNode = currentNode.nodeChildren.get(incrementor);
                    currentNode = parentNode;
                    currentNode.nodeChildren.get(incrementor).nodeChildren.add(newNode);
                }
                else
                {
                    parentNode = currentNode;
                    currentNode = currentNode.nodeChildren.iterator().next();
                    currentNode.nodeChildren.add(newNode);

                }
                incrementor = incrementor + 1;
            }
            System.out.println(rootNode.nodeChildren.size());
        }
    }

当第三个节点添加到树时,我得到一个 IndexOutOfBounds 异常

【问题讨论】:

  • 学习调试对于自己找出此类错误大有帮助。
  • 使用了 Eclipse 调试器,但谢谢

标签: java data-structures tree nodes indexoutofboundsexception


【解决方案1】:
while (currentNode.nodeChildren.size() < 3)

会导致

if (currentNode.nodeChildren.size() == 3)

总是评估为假,因此父节点永远不会切换到子节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多