Sunday, August 23, 2020

Case study: Mock interview - construct binary tree using post order traversal and inorder traversal list

 Here is the link. 



/*
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
*/

#include <iostream>
using namespace std;
// To execute C++, please define "int main()"
int main() {
auto words = { "Hello, ", "World!", "\n" };
for (const string& word : words) {
cout << word;
}
return 0;
}
TreeNode* constructTreeUtil(vector<int> in, vector<int> post, int inStrt,
int inEnd, int& idx, unordered_map<int,int>& um){
if(inStrt > inEnd) return nullptr;
int curr = post[idx];
auto node = TreeNode(curr); // root node
idx--;
if(inStrt == inEnd) return node;// one node - tree with size one ndoe
int inIdx = um[curr]; // inorder index
// node->right? why you put node.right first?
// 3 -> 20 - > 7 root node -> right -> right ->
// 20's left 15
// 3's left
node->right = constructTreeUtil(in, post, inIdx+1, inEnd, idx, um);
node->left = constructTreeUtil(in, post, inStrt, inIdx-1, idx, um);
return node;
}
TreeNode* constructTree(vector<int> in, vector<int> post){
unordered_map<int,int>um;
for(int i=0; i < in.size(); ++i){
mp[in[i]] = i;
}
int idx = in.size()-1;
return constructTreeUtil(in, post, 0, in.size()-1, idx, um);
}


Interviewer's feedback



No comments:

Post a Comment