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

LeetCode "Construct Binary Tree from Inorder and Postorder Traversal"

时间:2014-07-23 12:01:56      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   

Another textbook problem. We take back of postorder array as the current root, and then we can split the inorder array: 1st half for current right child, and 2nd for current left.

class Solution {
public:
    TreeNode *_buildTree(int in[], int i0, int i1, int insize, int post[], int &inx_p)
    {
        if(inx_p < 0 || i0 > i1) return NULL;

        TreeNode *pRoot = new TreeNode(post[inx_p]);

        int iRoot = std::find(in, in + insize, post[inx_p--]) - in;
        TreeNode *pRight = _buildTree(in, iRoot + 1, i1, insize, post, inx_p);
        pRoot->right = pRight;
        TreeNode *pLeft= _buildTree(in, i0, iRoot-1, insize, post, inx_p);
        pRoot->left = pLeft;
        return pRoot;
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int *in = new int[inorder.size()];
        std::copy(inorder.begin(), inorder.end(), in);
        int *post = new int[postorder.size()];
        std::copy(postorder.begin(), postorder.end(), post);
        int inx = postorder.size() - 1;
        return _buildTree(in, 0, inorder.size()-1, inorder.size(), post, inx);
    }
};

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   for   

原文地址:http://www.cnblogs.com/tonix/p/3862051.html

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