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

Construct Binary Tree from Preorder and Inorder Traversal

时间:2017-04-16 12:27:37      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:binary   and   ==   null   rsa   style   last   nbsp   first   

这里使用递归的算法,特别需要递归中边界的判断

/**
 * 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:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
    }
    
    typedef vector<int>::iterator inIterator;
    TreeNode* buildTree(inIterator prefirst, inIterator prelast, inIterator infirst, inIterator inlast)
    {
        if(prefirst == prelast)
            return nullptr;
        if(infirst == inlast)
            return nullptr;
            
        vector<int>::iterator iter = find(infirst, inlast, *prefirst);
        int dis = distance(infirst, iter);
        
        TreeNode *res = new TreeNode(*prefirst);
        
        res->left = buildTree(prefirst+1, prefirst+dis+1, infirst, iter);
        res->right = buildTree(prefirst+1+dis, prelast, iter+1, inlast);
        
        return res;
    }
};

 

Construct Binary Tree from Preorder and Inorder Traversal

标签:binary   and   ==   null   rsa   style   last   nbsp   first   

原文地址:http://www.cnblogs.com/chengyuz/p/6718187.html

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