Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The elegant recursive solution (in pseudo-code):</p> <pre><code>def sum (node): if node == NULL: return 0 return node-&gt;value + sum (node-&gt;left) + sum (node-&gt;right) </code></pre> <p>then just use:</p> <pre><code>total = sum (root) </code></pre> <p>This correctly handles the case of a NULL root node.</p> <hr> <p>And if you want to see it in action in C++, here's some code using that algorithm. First, the structure for a node and the <code>sum</code> function:</p> <pre><code>#include &lt;iostream&gt; typedef struct sNode { int value; struct sNode *left; struct sNode *right; } tNode; int sum (tNode *node) { if (node == 0) return 0; return node-&gt;value + sum (node-&gt;left) + sum (node-&gt;right); } </code></pre> <p>Then the code below is a test harness code for inserting nodes:</p> <pre><code>static tNode *addNode (tNode *parent, char leftRight, int value) { tNode *node = new tNode(); node-&gt;value = value; node-&gt;left = 0; node-&gt;right = 0; if (parent != 0) { if (leftRight == 'L') { parent-&gt;left = node; } else { parent-&gt;right = node; } } return node; } </code></pre> <p>And, finally, the main function for constructing the following tree, one that covers all of the valid possibilities (empty node, node with two children, node with no children, node with one right child and node with one left child):</p> <pre><code> 10 / \ 7 20 / \ 3 99 \ 4 \ 6 </code></pre> <p>The code to construct that tree and report the sum at various points is shown here:</p> <pre><code>int main (void) { // Empty tree first. tNode *root = 0; std::cout &lt;&lt; sum (root) &lt;&lt; '\n'; // Then a tree with single node (10). root = addNode (0, ' ', 10); std::cout &lt;&lt; sum (root) &lt;&lt; '\n'; // Then one with two subnodes (10, 7, 20). addNode (root,'L',7); addNode (root,'R',20); std::cout &lt;&lt; sum (root) &lt;&lt; '\n'; // Then, finally, the full tree as per above. addNode (root-&gt;left,'L',3); addNode (root-&gt;left-&gt;left,'R',4); addNode (root-&gt;left-&gt;left-&gt;right,'R',6); addNode (root-&gt;right,'R',99); std::cout &lt;&lt; sum (root) &lt;&lt; '\n'; return 0; } </code></pre> <p>This outputs (the correct):</p> <pre><code>0 10 37 149 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload