首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在java中创建树数据结构?

在java中创建树数据结构?
EN

Stack Overflow用户
提问于 2013-12-04 06:20:29
回答 1查看 11K关注 0票数 6

我试图在java中创建一个树数据结构,其中每个父节点只能有三个子节点,但是如果一个节点至少有一个子节点,但少于三个子节点,我就无法在树中添加一个节点。我不确定是否应该使用迭代器来迭代当前节点的节点列表。我尝试使用一个在每次调用add()方法时都会递增的变量。下面是我的代码: Node类:

代码语言:javascript
复制
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()方法

代码语言:javascript
复制
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异常

EN

回答 1

Stack Overflow用户

发布于 2013-12-04 06:25:33

代码语言:javascript
复制
while (currentNode.nodeChildren.size() < 3)

将导致

代码语言:javascript
复制
if (currentNode.nodeChildren.size() == 3)

始终计算为false,因此父节点永远不会切换到子节点。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20362913

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档