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

LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"

时间:2014-07-23 12:00:46      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   re   c   

A collegiate textbook problem. Nothing special, but just take care of your memory use.

class Solution {
public:
    TreeNode *_buildTree(int pre[], int &inx_p, int np, int in[], int i0, int i1)
    {
        if(inx_p == np || i0 == i1) return NULL;

        TreeNode *pRoot = new TreeNode(pre[inx_p]);
        
        int inx = std::find(in + i0, in + i1, pre[inx_p++]) - in;
        
        TreeNode *pLeft = _buildTree(pre, inx_p, np, in, i0, inx);
        TreeNode *pRight = _buildTree(pre, inx_p, np, in, inx + 1, i1);
        pRoot->left = pLeft; pRoot->right = pRight;
        return pRoot;

    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        int *pre = new int[preorder.size()];
        std::copy(preorder.begin(), preorder.end(), pre);
        int *in = new int[inorder.size()];
        std::copy(inorder.begin(), inorder.end(), in);
        int inx = 0;
        return _buildTree(pre, inx, preorder.size(), in, 0, inorder.size());
    }
};

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

LeetCode "Construct Binary Tree from Preorder and Inorder Traversal"

标签:style   blog   color   io   re   c   

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

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