1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[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());
    }
};