|
| 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