LeetCode——Construct Binary Tree from Inorder and Postorder Traversal

Question

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

参考:http://www.cnblogs.com/zhonghuasong/p/7096300.html

Code

/**
 * 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) {
        if (inorder.size() == 0 || postorder.size() == 0)
            return NULL;
        return ConstructTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    }
    
    TreeNode* ConstructTree(vector<int>& inorder, vector<int>& postorder, 
            int in_start, int in_end, int post_start, int post_end) {
        int rootValue = postorder[post_end];
        TreeNode* root = new TreeNode(rootValue);
        
        if (in_start == in_end) {
            if (post_start == post_end && inorder[in_start] == postorder[post_start])
                return root;
        }
        
        int rootIn = in_start;
        while (rootIn <= in_end && inorder[rootIn] != rootValue)
            rootIn++;
        
        int leftPostLength = rootIn - in_start;
        if (leftPostLength > 0) {
            // 注意起点和终点的写法
            root->left = ConstructTree(inorder, postorder, in_start, rootIn - 1, post_start, post_start + leftPostLength - 1);
        }
        if (leftPostLength < in_end - in_start) {
            root->right = ConstructTree(inorder, postorder, rootIn + 1, in_end, post_start + leftPostLength, post_end - 1);
        }
        
        return root;
    }
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/7096358.html