Skip to content

Commit

Permalink
added cpp solution to Tree-Construction
Browse files Browse the repository at this point in the history
  • Loading branch information
Arihant1467 committed Feb 24, 2019
1 parent 9bfb453 commit ebb130c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
3 changes: 0 additions & 3 deletions Graphs-And-Trees/Tree-Construction/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,5 @@ Postorder = [29,24,41,38,51,55,77,63,49]
#### Link to OJ
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

#### Link to Solution
https://github.com/Arihant1467/CompetitiveProgramming/tree/master/Tree-Construction/solution.py

---
Article contributed by [Arihant Sai](https://github.com/Arihant1467)
37 changes: 37 additions & 0 deletions Graphs-And-Trees/Tree-Construction/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {

public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {

return this->build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}

TreeNode* build(vector<int>& inorder,int iLeft,int iRight,vector<int>& postorder,int pLeft,int pRight){

if(pLeft>pRight){
return NULL;
}

int rootVal = postorder[pRight];
TreeNode* root = new TreeNode(rootVal);

auto it = std::find(inorder.begin()+iLeft,inorder.begin()+iRight,rootVal);
int indexInInorder = std::distance(inorder.begin(), it);

root->left = this->build(inorder,iLeft,indexInInorder-1,postorder,pLeft,pLeft+(indexInInorder-iLeft)-1);
root->right = this->build(inorder,indexInInorder+1,iRight,postorder,pLeft+(indexInInorder-iLeft),pRight-1);

return root;

}

};

0 comments on commit ebb130c

Please sign in to comment.