簡體   English   中英

在Java中創建樹形數據結構?

[英]Creating a tree data structure in java?

我試圖在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異常

while (currentNode.nodeChildren.size() < 3)

會引發

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

總是評估為false,因此父節點永遠不會切換到子節點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM