/** * 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) { return DFS(preorder,0,inorder,0,inorder.size()-1); } TreeNode* DFS(vector<int> preorder,int pos,vector<int> inorder,int ileft,int iright){ if(ileft > iright) return NULL; int i=0; for(i=ileft;i <= iright;i++){ if(preorder[pos] == inorder[i])break; } TreeNode* cur = new TreeNode(preorder[pos]); cur->left = DFS(preorder,pos+1,inorder,ileft,i-1); cur->right = DFS(preorder,pos+i-ileft+1,inorder,i+1,iright); return cur; } };