1. 程式人生 > >Construct Binary Tree from Preorder and Inorder Traversal

Construct Binary Tree from Preorder and Inorder Traversal

/**
 * 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>& preorder, vector<int>& inorder) {
        if(preorder.empty()) return NULL;
        return helper(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }
    TreeNode* helper(vector<int>& preorder, int pl, int pr, vector<int>& inorder, int il, int ir){
        if(pl>pr || il>ir) return NULL;
        int cur_val = preorder[pl];
        TreeNode* cur = new TreeNode(cur_val);
        int found = find(inorder.begin()+il, inorder.begin()+ir, cur_val)-(inorder.begin()+il);
        cur->left = helper(preorder, pl+1, pl+found, inorder, il, il+found-1);
        cur->right = helper(preorder, pl+1+found, pr, inorder, il+1+found, ir);
        return cur;
    }
};