-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary tree from inorder and postorder.txt
88 lines (61 loc) · 1.57 KB
/
binary tree from inorder and postorder.txt
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
Binary Tree From Inorder And Postorder
Problem Description
Given inorder and postorder traversal of a tree, construct the binary tree.
NOTE: You may assume that duplicates do not exist in the tree.
Problem Constraints
1 <= number of nodes <= 105
Input Format
First argument is an integer array A denoting the inorder traversal of the tree.
Second argument is an integer array B denoting the postorder traversal of the tree.
Output Format
Return the root node of the binary tree.
Example Input
Input 1:
A = [2, 1, 3]
B = [2, 3, 1]
Input 2:
A = [6, 1, 3, 2]
B = [6, 3, 2, 1]
Example Output
Output 1:
1
/ \
2 3
Output 2:
1
/ \
6 2
/
3
Example Explanation
Explanation 1:
Create the binary tree and return the root node of the tree.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
map<int,int> mp;
TreeNode* solve(vector<int> &A,vector<int> &B,int inStart,int inEnd,int pStart,int pEnd){
if(inStart>inEnd or pStart>pEnd){
return NULL;
}
TreeNode *temp=new TreeNode(B[pEnd]);
int index=(*mp.find(B[pEnd])).second;
int n=index-inStart;
temp->left=solve(A,B,inStart,index-1,pStart,pStart+n-1);
temp->right=solve(A,B,index+1,inEnd,pStart+n,pEnd-1);
return temp;
}
TreeNode* Solution::buildTree(vector<int> &A, vector<int> &B) {
mp.clear();
for(int i=0;i<A.size();i++){
mp[A[i]]=i;
}
int n=A.size();
return solve(A,B,0,n-1,0,n-1);
}