-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST_from_postorder.cpp
More file actions
58 lines (43 loc) · 1.13 KB
/
Copy pathBST_from_postorder.cpp
File metadata and controls
58 lines (43 loc) · 1.13 KB
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
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
Node* constructTree(int post[], int min_val, int max_val, int* i, int n){
if(*i<0){ return NULL; }
Node* root = NULL;
int curr = post[*i];
if(curr>min_val && curr<max_val){
root = new Node(curr);
if(*i>=0){
*i = *i - 1;
root->right = constructTree(post, curr, max_val, i, n);
root->left = constructTree(post, min_val, curr, i, n);
}
}
return root;
}
void printInorder(Node* root){
if(!root){return;}
if(root->left){printInorder(root->left);}
cout<<root->data<<" ";
if(root->right){printInorder(root->right);}
return;
}
int main() {
int post[] = {1, 7, 5, 50, 40, 10};
int n = sizeof(post) / sizeof(post[0]);
int index = n-1;
Node* root = constructTree(post, INT_MIN, INT_MAX, &index, n-1);
cout << "Inorder traversal: ";
printInorder(root);
return 0;
}