首页 > 其他 > 详细

LeetCode "Construct Binary Tree from Inorder and Postorder Traversal"

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

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"

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!