My C++ simple method with iterator

  • 0
    class Solution {
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            vector<int> ::iterator iter = preorder.begin();
            return helper(iter, inorder.begin(), inorder.end());
        TreeNode* helper(vector<int>::iterator &iter, const vector<int>::iterator &begin, const vector<int>::iterator &end){
            if(begin == end) return nullptr;
            auto pos = find(begin, end, *iter);
            TreeNode* root = new TreeNode(*iter);
            root->left = helper(iter, begin, pos);
            root->right = helper(iter, pos + 1, end);
            return root;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.