Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ok, I <em>think</em> this is doable with minimal data storage. This is only for completely balanced, filled-in trees. Extending it to one more element is easy (just print the extra last...), but more than that will take some more thought. Also, if your range isn't 1…N, but rather M…N, easy enough to just add M-1 to everything.</p> <ol> <li>The bottom row of the tree is 1, 1+2, 1+4, 1+6, etc.</li> <li>The second-from-bottom row of the tree is 2, 2+4, 2+8, etc.</li> <li>The third-from-bottom row of the tree is 4, 4+8, 4+16, etc.</li> <li>Etc.</li> </ol> <p>So, for a 1..(N-1) tree, where N is a power of two, we can first compute the height of the tree using log₂(N). For convenience, let n = N-1. The example tree is N=16:</p> <p>The first row (root) of the tree is ((n-1)/2)+1. Call this row 0. So you can go ahead and print that. The first element of the next row (row 1) is half of the first element of the previous row. And conveniently, the increment is the first value of the previous row. So for N=16, first element of row 2 = 4. You can print that. Next element is 4+8=12, which you can print. Since a row has 2*rownum elements, you're now done with row 0 (2**1 = 2) Next row starts out with half of what the previous row did, e.g. 2/2 = 2. It has 2**2 = 4 elements, with a increment of 4. So, 2, 6, 10, 14.</p> <pre><code> 8 4 12 2 6 10 14 1 3 5 7 9 11 13 15 </code></pre> <p>Now, if you want 1…16, you could just tack the extra element on the bottom right, so you'd output it last.</p> <p>Of course, instead of calling pow() all the time, you'd just multiply by 2 (which the compiler will turn to a bit-shift, if appropriate) to determine how many nodes this level. There are still going to be branches to test the loops, of course.</p> <p>I should warn you that I haven't had enough tea yet today, so this may be clearly silly. But it seems to work. At least in my head :-D</p>
    singulars
    1. This table or related slice is empty.
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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