Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The short answer is: you can't. A BST requires that the nodes follow the rule left &lt;= current &lt; right. In the example you linked: <a href="http://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_tree.svg" rel="noreferrer">http://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_tree.svg</a>, if you try and build a BST with the same shap you'll find that you can't.</p> <p>However if you want to stretch the definition of a BST so that it allows left &lt;= current &lt;= right (notice that here current &lt;= right is allowed, as apposed to the stricter definition) you can. Sort all the elements and stick them in an array. Now do an in-order traversal, replacing the values at nodes with each element in your array. Here's some pseudo code:</p> <pre><code>// t is your non-BST tree, a is an array containing the sorted elements of t, i is the current index into a index i = 0 create_bst(Tree t, Array a) { if(t is NIL) return; create_bst(t-&gt;left, a) t-&gt;data = a[i] i++ create_bst(t-&gt;right, a) } </code></pre> <p>The result won't be a true BST however. If you want a true BST that's as close to the original shape as possible, then you again put the elements in a sorted array but this time insert them into a BST. The order in which you insert them is defined by the sizes of the subtrees of the original tree. Here's some pseudo-code:</p> <pre><code>// left is initially set to 0 create_true_bst(Tree t, BST bt, array a, index left) { index i = left + left_subtree(t)-&gt;size bt-&gt;insert(a[i]) if(left_subtree(t)-&gt;size != 0) { create_true_bst(t-&gt;left, bt, a, left) create_true_bst(t-&gt;right, bt, a, i + 1) } } </code></pre> <p>This won't guarantee that the shape is the same however.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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