Skip to content

Commit d4874a1

Browse files
committed
Add solution #1008
1 parent 1af7e36 commit d4874a1

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Diff for: README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,084 LeetCode solutions in JavaScript
1+
# 1,085 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -816,6 +816,7 @@
816816
1005|[Maximize Sum Of Array After K Negations](./solutions/1005-maximize-sum-of-array-after-k-negations.js)|Easy|
817817
1006|[Clumsy Factorial](./solutions/1006-clumsy-factorial.js)|Medium|
818818
1007|[Minimum Domino Rotations For Equal Row](./solutions/1007-minimum-domino-rotations-for-equal-row.js)|Medium|
819+
1008|[Construct Binary Search Tree from Preorder Traversal](./solutions/1008-construct-binary-search-tree-from-preorder-traversal.js)|Medium|
819820
1009|[Complement of Base 10 Integer](./solutions/1009-complement-of-base-10-integer.js)|Easy|
820821
1010|[Pairs of Songs With Total Durations Divisible by 60](./solutions/1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium|
821822
1022|[Sum of Root To Leaf Binary Numbers](./solutions/1022-sum-of-root-to-leaf-binary-numbers.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1008. Construct Binary Search Tree from Preorder Traversal
3+
* https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers preorder, which represents the preorder traversal of a BST (i.e.,
7+
* binary search tree), construct the tree and return its root.
8+
*
9+
* It is guaranteed that there is always possible to find a binary search tree with the given
10+
* requirements for the given test cases.
11+
*
12+
* A binary search tree is a binary tree where for every node, any descendant of Node.left has
13+
* a value strictly less than Node.val, and any descendant of Node.right has a value strictly
14+
* greater than Node.val.
15+
*
16+
* A preorder traversal of a binary tree displays the value of the node first, then traverses
17+
* Node.left, then traverses Node.right.
18+
*/
19+
20+
/**
21+
* Definition for a binary tree node.
22+
* function TreeNode(val, left, right) {
23+
* this.val = (val===undefined ? 0 : val)
24+
* this.left = (left===undefined ? null : left)
25+
* this.right = (right===undefined ? null : right)
26+
* }
27+
*/
28+
/**
29+
* @param {number[]} preorder
30+
* @return {TreeNode}
31+
*/
32+
var bstFromPreorder = function(preorder) {
33+
let index = 0;
34+
return buildBST(Infinity);
35+
36+
function buildBST(bound) {
37+
if (index >= preorder.length || preorder[index] > bound) return null;
38+
39+
const node = new TreeNode(preorder[index++]);
40+
node.left = buildBST(node.val);
41+
node.right = buildBST(bound);
42+
43+
return node;
44+
}
45+
};

0 commit comments

Comments
 (0)