Skip to content

Commit 1c746ab

Browse files
Use HashMap so we don't need to "find"
1 parent 5a67c4f commit 1c746ab

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

106. Construct Binary Tree from Inorder and Postorder Traversal.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,50 @@ class Solution {
3737
return node;
3838
}
3939
};
40+
41+
//Use HashMap so we don't need to "find"
42+
//https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/34782/My-recursive-Java-code-with-O(n)-time-and-O(n)-space
43+
//Runtime: 24 ms, faster than 74.28% of C++ online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
44+
//Memory Usage: 24 MB, less than 36.01% of C++ online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
45+
/**
46+
* Definition for a binary tree node.
47+
* struct TreeNode {
48+
* int val;
49+
* TreeNode *left;
50+
* TreeNode *right;
51+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
52+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
53+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
54+
* };
55+
*/
56+
class Solution {
57+
public:
58+
unordered_map<int, int> val2idx;
59+
60+
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder, int is, int ie, int ps, int pe) {
61+
if(is > ie || ps > pe) return nullptr;
62+
63+
TreeNode* node = new TreeNode(postorder[pe]);
64+
65+
int iroot = val2idx[postorder[pe]];
66+
// cout << "inorder's root at: " << iroot << endl;
67+
int leftSize = iroot-is;
68+
69+
node->left = buildTree(inorder, postorder, is, iroot-1, ps, ps+leftSize-1);
70+
node->right = buildTree(inorder, postorder, iroot+1, ie, ps+leftSize, pe-1);
71+
72+
return node;
73+
};
74+
75+
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
76+
int n = inorder.size();
77+
78+
if(n == 0) return nullptr;
79+
80+
for(int i = 0; i < n; ++i){
81+
val2idx[inorder[i]] = i;
82+
}
83+
84+
return buildTree(inorder, postorder, 0, n-1, 0, n-1);
85+
}
86+
};

0 commit comments

Comments
 (0)