-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathbuildtreefrom_inorder_postorder.cpp
64 lines (62 loc) · 1.21 KB
/
buildtreefrom_inorder_postorder.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
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
#include<bits/stdc++.h>
#define ll long long
#define vi vector<int>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
Node* create(int data);
};
class Node* create(int data)
{
class Node *n=new Node;
n->data=data;
n->left=NULL;
n->right=NULL;
return n;
}
int search(int inorder[],int start,int end,int cur)
{
for(int i=start;i<=end;i++)
{
if(inorder[i]==cur)
return i;
}
return -1;
}
Node* buildtree(int postorder[],int inorder[],int start,int end){
static int ind=4;
if(start>end)
{return NULL;}
int val=postorder[ind];
ind--;
Node *cur=new Node;
cur=create(val);
if(start==end)
return cur;
int pos=search(inorder,start,end,val);
cur->right=buildtree(postorder,inorder,pos+1,end);
cur->left=buildtree(postorder,inorder,start,pos-1);
return cur;
}
void printinorder(Node* root)
{
if(root==NULL)
return;
printinorder(root->left);
cout<<root->data<<" ";
printinorder(root->right);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int inorder[]={4,2,1,5,3};
int postorder[]={4,2,5,3,1};
Node *root=buildtree(postorder,inorder,0,4);
printinorder(root);
return 0;
}