Monday, October 21, 2013

Construct Binary Tree from Inorder and Postorder Traversal [Leetcode]

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: the postorder traversal of a tree is in the form of <left subtree, right subtree, root>, while the inorder traversal of a tree is in the form of <left subtree, root, right subtree>. To solve this problem, we first need to find out the position of the root in the inorder traversal, and then solve the subtrees recursively. [the same idea as the solution to Construct Binary Tree from Preorder and Inorder Traversal
/**
 * 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 *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(inorder.size()!=postorder.size() || inorder.size()==0)
            return NULL;
        int curVal = postorder.back();
        //to find out the position of the root
        // to speed up the search, we can do binary search or hashtable)
        int i=0;
        while(i<inorder.size()){
            if(inorder[i]==curVal)
                break;
            ++i;
        }
        
        vector<int> inR(inorder.begin()+i+1, inorder.end());
        inorder.erase(inorder.begin()+i, inorder.end());
        //vector<int> inL(inorder.begin(), inorder.begin()+i);

        vector<int> postR(postorder.begin()+i, postorder.end()-1);
        //vector<int> postL(postorder.begin(), postorder.begin()+i);
        postorder.erase(postorder.begin()+i, postorder.end());
        
        TreeNode* root = new TreeNode(curVal);
        root->left = buildTree(inorder, postorder);
        root->right = buildTree(inR, postR);
        return root;
    }
};

No comments:

Post a Comment