105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

==============

基本功:

利用前序和中序构建二叉树

,

===

code

/**
 * 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:
    ///help_buildTree_pi()
    template<typename Iteratorr>
    TreeNode *help_buildTree_pi(Iteratorr pre_first,Iteratorr pre_last,
        Iteratorr in_first,Iteratorr in_last){
        if(pre_first == pre_last) return nullptr;
        if(in_first == in_last) return nullptr;

        auto root = new TreeNode(*pre_first);
        auto inRootPos = find(in_first,in_last,*pre_first);
        auto leftSize = distance(in_first,inRootPos);

        root->left = help_buildTree_pi(next(pre_first),next(pre_first,leftSize+1),
                                        in_first,next(in_first,leftSize));
        root->right = help_buildTree_pi(next(pre_first,leftSize+1),pre_last,next(inRootPos),in_last);
        return root;
    }
    TreeNode* buildTree_pi(vector<int> &preorder,vector<int> &inorder){
        return help_buildTree_pi(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
    }
};
原文地址:https://www.cnblogs.com/li-daphne/p/5618802.html