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

LeetCode Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-07-16 18:23:21      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   div   

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int ilen = inorder.size();
        int plen = postorder.size();

        if (ilen == 0 || plen == 0) return NULL;
        return dfs(inorder, postorder, 0, ilen, plen - 1, -1);
    }

    TreeNode* dfs(vector<int> &inorder, vector<int> &postorder, int is, int ie, int ps, int pe) {
        
        if (is >= ie || ps <= pe) return NULL;
        int rval = postorder[ps];
        int iroot= is;

        while (iroot != ie && inorder[iroot] != rval) iroot++;

        int left_len = iroot - is;
        
        TreeNode* nroot = new TreeNode(rval);

        nroot->left = dfs(inorder, postorder, is, iroot, pe + left_len, pe);
        nroot->right= dfs(inorder, postorder, iroot + 1, ie, ps - 1, pe + left_len);

        return nroot;
    }
};

 

LeetCode Construct Binary Tree from Inorder and Postorder Traversal,布布扣,bubuko.com

LeetCode Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   color   os   io   div   

原文地址:http://www.cnblogs.com/lailailai/p/3845349.html

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