Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Does the tree have to be balanced? Does the algorithm need to be efficient?</p> <p>If not, then the simplest thing to do is make a tree in which all the left children are null, i.e., a tree that devolves to a linked list.</p> <p>To insert, recursively look go to the right child, and then update the size of the node on the way back out. Something like (pseudocode)</p> <pre><code>function insert(node, value, index, depth) if depth &lt; index create the rightchild if necessary insert( rightchild, value, index, depth + 1) if depth == size node.value = value node.size = rightchild.size + 1 </code></pre> <p>After you have this working, you can modify it to be more balanced. When increasing the length of the list, add nodes to the left or right child nodes depending on which currently has the least, and update the size on the way out of the recursion.</p> <p>To generalize to be more efficient, you need to work on the index in terms of its binary representation.</p> <p>For example, and empty list has one node, without children with value null and size 0.</p> <p>Say you want to insert "hello" at index 1034. Then you want to end up with a tree whose root has two children, with sizes 1024 and 10. The left child has no actual children, but the right node has a right child of its own of size 2. (The left of size 8 is implied.) That node in turn, has one right child of size 0, with the value "hello". (This list has a 1-based index, but a 0-based index is similar.)</p> <p>So you need to recursively break down the index into its binary parts, and add nodes as necessary. When searching the list, you need to take care when traversing a node with null children</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.
    1. This table or related slice is empty.
    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