Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class Solution { public: void f(vector<int> &preorder,int s1, int e1,vector<int> & inorder,int s2, int e2, TreeNode *& root){ if (s1 > e1){ return; } if (!root){ root = new TreeNode(preorder[s1]); int m = s2; for(;m <= e2;m++){ if (inorder[m] == preorder[s1]){ break; } } f(preorder,s1 + 1,s1 + 1 + m - 1 - s2,inorder,s2,m-1,root->left); f(preorder,e1 - (e2 - m - 1),e1,inorder,m+1,e2,root->right); } } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!preorder.size()){ return NULL; } TreeNode * root = NULL; f(preorder,0,preorder.size() -1,inorder,0,inorder.size() -1,root); return root; } };