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 binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* visit(vector<int> &inorder, int lbegin, int lend, vector<int> &postorder, int rbegin, int rend, map<int, int> &table)
    {
        if (lbegin > lend)
        {
            return NULL;
        }
        TreeNode *root = new TreeNode(postorder[rend]);
        int pos = table[postorder[rend]];
        int offset = pos - lbegin - 1;
        root->left = visit(inorder, lbegin, pos-1, postorder, rbegin, rbegin+offset, table);
        root->right = visit(inorder, pos+1, lend, postorder, rbegin+offset+1, rend-1, table);
        return root;
    }
        
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int size = inorder.size();
        if (size < 1)
        {
            return NULL;
        }
    
        map<int, int> table;
        for (int i = 0; i < size; i++)
        {
            table[inorder[i]] = i;
        }

        return visit(inorder, 0, size-1, postorder, 0, size-1, table);
    }
};


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