# Reconstruct Bst

![](/files/AWTmXryeUYRs85q1Cb6X)

* n, n (need to create n bst nodes)

```jsx
// This is an input class. Do not edit.
class BST {
  constructor(value, left = null, right = null) {
    this.value = value;
    this.left = left;
    this.right = right;
  }
}

class IterIndex {
  constructor(value) {
    this.index = value;
  }
}

function reconstructBst(preOrderTraversalValues) {
  const trace = new IterIndex(0);
  const bst = buildBst(preOrderTraversalValues, trace);
  return bst;
}

function buildBst(arr, trace, min = -Infinity, max = Infinity) {
  if (trace.index >= arr.length) {
    return null;
  }

  const value = arr[trace.index];
  if (value < min || value >= max) 
    return null;

  trace.index += 1;
  const bst = new BST(value);
  bst.left = buildBst(arr, trace, min, value);
  bst.right = buildBst(arr, trace, value, max);

  return bst;
}

// Do not edit the lines below.
exports.BST = BST;
exports.reconstructBst = reconstructBst;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/reconstruct-bst.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
