Leetcode::Construct Binary Tree from Inorder and Postorder Traversal
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *build( vector<int>&inorder, vector<int> &postorder,int in_s,int in_e, int pos_s, int pos_e) { if( in_s >= in_e ) { return NULL; } int val = postorder[pos_e-1]; TreeNode * tmp=new TreeNode(val); int i; for(i=in_s; i< in_e ; i++ ) { if( val == inorder[i]) { break; } } int len = i - in_s; tmp->left=build(inorder,postorder,in_s,i,pos_s ,pos_s + len); tmp->right=build(inorder,postorder,i+1,in_e,pos_s+len,pos_e -1); return tmp; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function return build(inorder,postorder,0,inorder.size(),0,postorder.size()); } };