[LeetCode] Construct Binary Search Tree from Preorder Traversal

1008. Construct Binary Search Tree from Preorder Traversal

Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
TreeNode* build(vector<int>& order, int& n, int parent) {
if(n == order.size() || order[n] > parent) return nullptr;
TreeNode* node = new TreeNode(order[n++]);
node->left = build(order, n, node->val);
node->right = build(order, n, parent);
return node;
}
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
int n = 0;
return build(preorder, n, INT_MAX);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/06/PS/LeetCode/construct-binary-search-tree-from-preorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.