-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConstructBinaryTreefromInorderandPostorderTraversal_106.cpp
53 lines (41 loc) · 1.61 KB
/
ConstructBinaryTreefromInorderandPostorderTraversal_106.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
/*
~ Author : leetcode.com/tridib_2003/
~ Problem : 106. Construct Binary Tree from Inorder and Postorder Traversal
~ Link : https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int postIdx = 0;
int searchNode(vector<int> inorder, int start, int end, int value) {
for (int i = start; i <= end; ++i)
if (inorder[i] == value)
return i;
return -1;
}
TreeNode* buildTreeHelper(vector<int> inorder, vector<int> postorder, int startIdx, int endIdx) {
if (startIdx > endIdx)
return NULL;
TreeNode *newNode = new TreeNode(postorder[postIdx--]);
if (startIdx == endIdx)
return newNode;
int pos = searchNode(inorder, startIdx, endIdx, newNode -> val);
newNode -> right = buildTreeHelper(inorder, postorder, pos + 1, endIdx);
newNode -> left = buildTreeHelper(inorder, postorder, startIdx, pos - 1);
return newNode;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
postIdx = postorder.size() - 1;
return buildTreeHelper(inorder, postorder, 0, inorder.size() - 1);
}
};