forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PreorderToBST.cpp
35 lines (33 loc) · 906 Bytes
/
PreorderToBST.cpp
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
#include <iostream>
using namespace std;
class Solution
{
public:
Node *solve(int pre[], int mini, int maxi, int &index, int n)
{
if (index >= n)
{
return NULL;
}
// check for out of range
if (pre[index] < mini || pre[index] > maxi)
{
return NULL;
}
// we are in range now
// recursive calls
Node *root = newNode(pre[index++]);
root->left = solve(pre, mini, root->data, index, n);
root->right = solve(pre, root->data, maxi, index, n);
return root;
}
// Function that constructs BST from its preorder traversal.
Node *post_order(int pre[], int size)
{
// code here
int mini = INT_MIN;
int maxi = INT_MAX;
int index = 0;
return solve(pre, mini, maxi, index, size);
}
};