a simple c++ method using iterator (little modification from preorder one)


  • 0
    Y
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            vector<int> ::reverse_iterator iter = postorder.rbegin();
            return helper(iter, inorder.begin(), inorder.end());
        }
        TreeNode* helper(vector<int>::reverse_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);
            iter++;
            root->right = helper(iter, pos + 1, end);
            root->left = helper(iter, begin, pos);
            return root;
        }
    };
    

    the link of preorder one https://discuss.leetcode.com/topic/104481/my-c-simple-method-with-iterator


Log in to reply
 

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