[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

和上一题同理,不过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());
    }
};

 

你可能感兴趣的:(LeetCode)