The time complexity of above solution is O(n2) and takes O(n) extra space for the call stack. We can reduce the time complexity to O(n) by following a different approach that doesn’t involve searching for index which separates the keys of left and right sub-tree in preorder sequence.

We know that in a BST, each node has key which is greater than all keys present in its left sub-tree, and less than the keys present in the right sub-tree. The idea to pass the information regarding the valid range of keys for current root node and its children in the recursion itself.

We start by setting the range as [INT_MIN, INT_MAX] for the root node. This means that the root node and any of its children can have keys in the ranging between INT_MIN and INT_MAX. Like previous approach, we construct the root node of BST from the first item in the preorder sequence. Suppose the root node has value x, we recur for right sub-tree with range (x, INT_MAX) and recur for left sub-tree with range [INT_MIN, x). To construct the complete BST, we recursively set the range for each recursive call and simply return if next element of preorder traversal is out of the valid range.

Here’s a C++ program that demonstrates it:

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

#include <iostream>

#include <vector>

#include <climits>

usingnamespacestd;

// Data structure to store a Binary Tree node

structNode{

intdata;

Node*left,*right;

};

// Function to create a new binary tree node having given key

Node*newNode(intkey)

{

Node*node=newNode;

node->data=key;

node->left=node->right=nullptr;

returnnode;

}

// Function to print the inorder traversal of a binary tree

voidinorder(Node*root)

{

if(root==nullptr)

return;

inorder(root->left);

cout<<root->data<<' ';

inorder(root->right);

}

// Recursive function to build a BST from a preorder sequence

Node*buildTree(vector<int>const&preorder,int&pIndex,

intmin,intmax)

{

// Base case

if(pIndex==preorder.size())

returnnullptr;

// Return if next element of preorder traversal is not in the valid range