Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning recursive ternary freaks out
    primarykey
    data
    text
    <p>assume this following function:</p> <pre><code>int binaryTree::findHeight(node *n) { if (n == NULL) { return 0; } else { return 1 + max(findHeight(n-&gt;left), findHeight(n-&gt;right)); } } </code></pre> <p>Pretty standard recursive <code>treeHeight</code> function for a given binary search tree <code>binaryTree</code>. Now, I was helping a friend (he's taking an algorithms course), and I ran into some weird issue with this function that I couldn't 100% explain to him.</p> <p>With max being defined as <code>max(a,b) ((a)&gt;(b)?(a):(b))</code> (which happens to be the max definition in <code>windef.h</code>), the recursive function freaks out (it runs something like <code>n^n</code> times where <code>n</code> is the tree height). This obviously makes checking the height of a tree with 3000 elements take very, very long.</p> <p>However, if max is defined via templating, like <code>std</code> does it, everything is okay. So using <code>std::max</code> fixed his problem. I just want to know why.</p> <p>Also, why does the <code>countLeaves</code> function work fine, using the same programmatic recursion?</p> <pre><code>int binaryTree::countLeaves(node *n) { if (n == NULL) { return 0; } else if (n-&gt;left == NULL &amp;&amp; n-&gt;right == NULL) { return 1; } else { return countLeaves(n-&gt;left) + countLeaves(n-&gt;right); } } </code></pre> <p>Is it because in returning the ternary function, the values <code>a =&gt; countLeaves(n-&gt;left)</code> and <code>b =&gt; countLeaves(n-&gt;right)</code> were recursively double called simply because they were the resultants?</p> <p>Thank you!</p> <h2>The question was answered below</h2> <p>I just wanted to link some literature on the subject for future reference:<br> <a href="http://www.boostpro.com/tmpbook/preprocessor.html" rel="nofollow noreferrer">http://www.boostpro.com/tmpbook/preprocessor.html</a><br> <a href="http://msdn.microsoft.com/en-us/library/z3f89ch8.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/z3f89ch8.aspx</a></p> <p>The main difference between the two implementations being:</p> <pre><code>#define max(i, j) (((i) &gt; (j)) ? (i) : (j)) </code></pre> <p>vs</p> <pre><code>template&lt;class T&gt; T max (T i, T j) { return ((i &gt; j) ? i : j) } </code></pre> <p><strong>Thank you all!</strong></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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