簡體   English   中英

通過基於級別的樹遍歷另一個樹來創建 n 叉樹

[英]Creation of a n-ary tree through level based tree traversal of another

因此,我正在逐級遍歷具有屬性 id 和 name 的節點的 n-ary 樹,我想更改每個節點的名稱並使用更改的節點創建另一個類似的 n-ary 樹(根節點具有A作為id

    Queue<Node> queue = new LinkedList<>();
    // node being the root node of the already created n-ary tree
    queue.add(node);
    Node rootOut = new Node(node.id,node.name);
    Node copiedNode = null;
    Node resNode = null;
    // iterate while queue not empty
    while(!queue.isEmpty()){

        // dequeue
        Node next = queue.remove();
    
 
        
        copiedNode = new Node(next.id,next.name);
        for (Node child : next.children) {
           

            Node copiedChildNode = new Node(child.id,child.name);
            copiedNode.children.add(copiedChildNode);
            if (next.id == "A") rootOut = copiedNode;
            queue.add(child);
        }
    }
    return rootOut ;

但這不會返回正確的新樹的根節點。 實際上,這僅返回根節點及其直接子節點,但沒有進一步的深度。 任何人都可以幫助正確地做到這一點

您的嘗試沒有跟蹤您正在制作的副本,因此您沒有構建樹,只是一堆單節點副本及其子節點:

    queue.add(node);
    Node copiedNode = null;

    while(!queue.isEmpty()){
        Node next = queue.remove();

        // A new copy (not being referenced by anything)
        copiedNode = new Node(next.id,next.name);
        for (Node child : next.children) {
           

            // A new copy (referenced by only the aforementioned copy
            Node copiedChildNode = new Node(child.id,child.name);
            copiedNode.children.add(copiedChildNode);

            // If the original was "A", store a reference to the copy.
            if (next.id == "A") rootOut = copiedNode;

            // The original is queued, not the copy
            queue.add(child);
        }
    }
 
    // Return only the shallow copy
    return rootOut ;

您需要在副本中構建一個結構,跟蹤引用:

    Queue<Node> queue = new LinkedList<>();
    queue.add(node);
    Node rootOut = new Node(node.id,node.name);

    // For tracking copies
    Map<String, Node> copiedNodesById = new HashMap<>();
    copiedNodesById.put(rootOut.id, rootOut);

    while(!queue.isEmpty()){

        Node currentOriginal = queue.remove();
        // Get an existing copy rather than making a new one.
        Node currentCopy = copiedNodesById.get(currentOriginal.id);
        
        for (Node childOriginal : currentOriginal.children) {

            Node copiedChildNode = new Node(childOriginal.id,childOriginal.name);
            currentCopy.children.add(copiedChildNode);

            // Track the copy that was just made.
            copiedNodesById.put(copiedChildNode.id, copiedChildNode);
            
            if (next.id == "A") rootOut = currentCopy;
            queue.add(childOriginal);
        }
    }
    return rootOut ;

我冒昧地重命名了一些變量,以使原始與副本更清楚。

復制的節點也可能在另一個隊列中被跟蹤。 或者隊列可以改為跟蹤(原始、復制)元組。

至於基於“A”的位置重構副本,我將把它留給你,因為我不清楚 function 應該如何。

暫無
暫無

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

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