-
Notifications
You must be signed in to change notification settings - Fork 82
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added cpp solution to Tree-Construction
- Loading branch information
1 parent
9bfb453
commit ebb130c
Showing
2 changed files
with
37 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
} | ||
|
||
}; |