[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

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

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

Solution:

/**
 * 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 *built(vector<int> &inorder, vector<int> &postorder, int in_start, int in_end, int post_start, int post_end)
    {
        if(in_start > in_end || post_start > post_end) 
            return NULL;
        TreeNode *curRoot = new TreeNode(postorder[post_end]);
        int rootIndex = -1;
        for(int i = in_end;i >= in_start;i--)
        {
            if(inorder[i] == postorder[post_end])
            {
                rootIndex = i;
                break;
            }
        }
        if(rootIndex == -1) return NULL;
        int leftNum = rootIndex - in_start;
        curRoot -> left = built(inorder, postorder, in_start, rootIndex - 1, post_start, post_start + leftNum - 1);
        curRoot -> right = built(inorder, postorder, rootIndex + 1, in_end, post_start + leftNum, post_end - 1);
        return curRoot;
    }

    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        return built(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); 
    }
};
原文地址:https://www.cnblogs.com/changchengxiao/p/3619739.html