在java中创建树数据结构?

 书友41494390_263 发布于 2023-02-13 09:21

我试图在java中创建一个树数据结构,其中每个父节点只能有三个子节点,但在节点至少有一个子节点但少于3个子节点的情况下,我一直坚持在树上添加一个节点.我不确定是否应该使用迭代器来迭代我当前节点的节点列表.我尝试使用一个每次add()调用方法时都会增加的变量.这是我的代码:Node class:

public class Node {

    int keyValue;
    int nodeLabel;
    ArrayList nodeChildren;

    private static int count;

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

    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异常

1 个回答
  • while (currentNode.nodeChildren.size() < 3)
    

    会引发

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

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

    2023-02-13 09:26 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有