簡體   English   中英

如何以樹數據結構將數據傳遞給其子級

[英]How to pass data to its children in tree data structure

如何遍歷此樹數據結構,將值傳遞給javascript中的子級。 百分比用於將值傳遞拆分為“ N”和“ Y”

這是圖片 在此處輸入圖片說明

在不知道您的數據結構的情況下,我將提出一個使用Node類的屬性,該類具有以下屬性:

  • 分數(0到1之間的數字的百分比),
  • 兩個子節點引用(一個表示“否”,一個表示“是”),以及
  • 該值首先為0,但一旦完成計算就可以確定。

該算法將是一種遞歸算法,您從根開始並為其輸入1000。 該節點將小數應用於該值(即乘),並將結果添加到其自己的值。 然后,將該值遞歸輸入到“是”子代(如果有),其余值遞歸輸入到“否”子代。

重要的是, 添加到節點的現有值,因為某些節點可能會從多個“父級”獲得輸入,如示例圖右側所示。 這些多個輸入應加起來。

這是JavaScript代碼:

 class Node { constructor(fraction) { this.fraction = fraction; // number between 0 and 1 this.no = null; // child node for edge with label "N" this.yes = null; // child node for edge with label "Y" this.value = 0; // This will get a value later, as input is cascaded through the graph } setChildren(no, yes) { this.no = no; this.yes = yes; } addInput(value) { const addedValue = value * this.fraction; this.value += addedValue; if (value) { // dripple down the value through the outward edges if (this.no) this.no.addInput(value - addedValue); if (this.yes) this.yes.addInput(addedValue); } } } // Create vertices with their percentages (fractions) const nodes = [ new Node(1), new Node(0.5), new Node(0.8), new Node(1), new Node(0.13), new Node(0.5), new Node(1), new Node(0.3) ]; // Create edges nodes[0].setChildren(null, nodes[1]); nodes[1].setChildren(nodes[2], nodes[5]); nodes[2].setChildren(nodes[3], nodes[4]); nodes[4].setChildren(null, nodes[5]); nodes[5].setChildren(nodes[6], nodes[7]); // Send a value of 1000 to the root node nodes[0].addInput(1000); // Show the value of each node after this action console.log("node value"); for (const node of nodes) { console.log((node.fraction*100 + "%").padStart(4), node.value.toFixed(1).padStart(6)); } 

一些評論

盡管此問題討論的是樹數據結構,並用treetree-traversal標記,但輸入圖不是樹,而是DAG

在評論中提到,百分比值用於拆分將要到達下一個圓的值,但是在圖中,百分比也應用於節點本身 :百分比為30%的葉子接收的值為276,但是但是圖像顯示該節點的值已應用30%。

暫無
暫無

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

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