leetcode——106——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.


/**
 * 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 Helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    TreeNode* Helper(vector<int> &inorder, int begin1, int end1, vector<int> &postorder, int begin2, int end2)
    {
        if(begin2 > end2)
            return NULL;
        else if(begin2 == end2)
            return new TreeNode(postorder[end2]);
            
        TreeNode* root = new TreeNode(postorder[end2]);
        int i = begin1;
        for(; i <= end1; i ++)
        {
            if(inorder[i] == postorder[end2])
                break;
        }
        //inorder[i] is the root
        int leftlen = i-begin1;
        
        root->left = Helper(inorder, begin1, begin1+leftlen-1,postorder, begin2, begin2+leftlen-1);
        root->right = Helper(inorder,begin1+leftlen+1, end1, postorder, begin2+leftlen,end2-1);
        return root;
    }
};

你可能感兴趣的:(leetcode——106——Construct Binary Tree from Inorder and Postorder Traversal)