[leetcode]Construct Binary Tree from Inorder and Postorder Traversal
Posted on 2014-01-14 18:05 1957 阅读(205) 评论(0) 编辑 收藏 举报和上一题同理,不过root在postorder的最后
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: template<typename Iter> TreeNode* make(Iter iFirst , Iter iLast , Iter pFirst , Iter pLast) { if(iFirst == iLast) return nullptr; if(pFirst == pLast) return nullptr; pLast--; Iter iRoot = find(iFirst , iLast , *pLast); TreeNode* root = new TreeNode(*iRoot); int leftSize = iRoot - iFirst; root -> left = make(iFirst , iRoot , pFirst , pFirst + leftSize); root -> right = make(iRoot+1 , iLast , pFirst + leftSize , pLast); return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if(inorder.size() == 0) return nullptr; return make(inorder.begin() , inorder.end() , postorder.begin() , postorder.end()); } };
by 1957