2.Construct Binary Tree from Preorder and Inorder Traversal

https://leetcode.com/problems/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:
    typedef vector::iterator Iter;

    TreeNode* buildTree(vector& preorder, vector& inorder) {
        return buildTree(inorder.begin(), inorder.end(), preorder.begin(), preorder.end());
    }

    TreeNode *buildTree(Iter istart, Iter iend, Iter pstart, Iter pend) {
        if (istart == iend) {
            return nullptr;
        }

        TreeNode* node = new TreeNode(*pstart);
        
        Iter ipos = find(istart, iend, *pstart);
        node->left = buildTree(istart, ipos, pstart+1, pstart+(ipos-istart)+1);
        node->right = buildTree(ipos+1, iend, pstart+(ipos-istart)+1, pend);

        return node;
    }
};

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