Construct Binary Tree from Preorder and Inorder Traversal @LeetCode
PROBLEM :
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (Recursive Solution)
--------------------------------------------------------------------------------
/**
* 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>& preorder, vector<int>& inorder) {
TreeNode* root ;
int size=inorder.size() ;
if(size==0)
return NULL ;
size=0 ;
root=BuiltPostOrderTree(inorder,preorder,0,inorder.size()-1,&size) ;
return root ;
}
TreeNode* BuiltPostOrderTree(vector<int> &inorder,vector<int> &preorder,int begin,int end,int *curr){
if(begin>end)
return NULL ;
TreeNode* root=new TreeNode(preorder[(*curr)++]);
if(begin==end)
return root ;
int index=FindIndex(inorder,root->val) ;
root->left=BuiltPostOrderTree(inorder,preorder,begin,index-1,&(*curr)) ;
root->right=BuiltPostOrderTree(inorder,preorder,index+1,end,&(*curr)) ;
return root ;
}
int FindIndex(vector<int> &inorder,int data){
for(int i=0;i<inorder.size();i++){
if(inorder[i]==data)
return i ;
}
}
};
---------------------------------------------------------------------------------
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (Recursive Solution)
--------------------------------------------------------------------------------
/**
* 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>& preorder, vector<int>& inorder) {
TreeNode* root ;
int size=inorder.size() ;
if(size==0)
return NULL ;
size=0 ;
root=BuiltPostOrderTree(inorder,preorder,0,inorder.size()-1,&size) ;
return root ;
}
TreeNode* BuiltPostOrderTree(vector<int> &inorder,vector<int> &preorder,int begin,int end,int *curr){
if(begin>end)
return NULL ;
TreeNode* root=new TreeNode(preorder[(*curr)++]);
if(begin==end)
return root ;
int index=FindIndex(inorder,root->val) ;
root->left=BuiltPostOrderTree(inorder,preorder,begin,index-1,&(*curr)) ;
root->right=BuiltPostOrderTree(inorder,preorder,index+1,end,&(*curr)) ;
return root ;
}
int FindIndex(vector<int> &inorder,int data){
for(int i=0;i<inorder.size();i++){
if(inorder[i]==data)
return i ;
}
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment