码迷,mamicode.com
首页 > 其他好文 > 详细

105. Construct Binary Tree from Preorder and Inorder Traversal

时间:2016-06-26 23:57:45      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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

 

105. Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5618802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!