原题传送门—>>


Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:

3

/ \
9 20
/ \
15 7

和105题如出一辙,不过这次我换种方式,避免了反复生成vector对象。
并且这种方式比较容易改成c代码吧

/**
 * 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>& inorder, vector<int>& postorder) {
        return buildTree(inorder, 0, inorder.size(), postorder, 0, postorder.size());
    }

    /*这几个参数分别是:中序遍历序列,中序遍历起点,中序遍历终点(不包含该点) 、后序遍历序列、起点、终点*/
    TreeNode* buildTree(vector<int>& inorder, int s_in, int e_in, vector<int>& postorder, int s_po, int e_po)
    {
        if(s_in >= e_in)
        {
            return NULL;
        }
        TreeNode* root = new TreeNode(postorder[e_po - 1]);
        int leftSize = find(inorder.begin()+s_in, inorder.begin()+e_in, postorder[e_po - 1]) - inorder.begin() - s_in;
        root->left = buildTree(inorder, s_in, s_in+leftSize, postorder, s_po, s_po+leftSize);
        root->right = buildTree(inorder, s_in+1+leftSize, e_in, postorder, s_po+leftSize,e_po-1);
        return root;
    }
};