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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2017-04-16 12:13:43      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:amp   efi   struct   blog   null   中序   nod   bin   class   

方法和依据前序和中序遍历确定二叉树一致。

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

 

Construct Binary Tree from Inorder and Postorder Traversal

标签:amp   efi   struct   blog   null   中序   nod   bin   class   

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

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