积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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());
    }
};

 

posted on 2016-06-26 22:46  x7b5g  阅读(218)  评论(0编辑  收藏  举报