[英]How to pass data to its children in tree data structure
在不知道您的數據結構的情況下,我將提出一個使用Node類的屬性,該類具有以下屬性:
該算法將是一種遞歸算法,您從根開始並為其輸入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)); }
盡管此問題討論的是樹數據結構,並用tree
和tree-traversal
標記,但輸入圖不是樹,而是DAG 。
在評論中提到,百分比值用於拆分將要到達下一個圓的值,但是在圖中,百分比也應用於節點本身 :百分比為30%的葉子接收的值為276,但是但是圖像顯示該節點的值已應用30%。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.