牛客网-剑指offer-重建二叉树

运行时间:7ms

占用内存:476k

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector pre,vector vin) {
        int lenv = vin.size();
        if(lenv == 0)
            return NULL;
        vector left_pre, right_pre, left_vin, right_vin;
        TreeNode *head = new TreeNode(pre[0]);
        int gen = 0;
        for(int i = 0; i < lenv; i++)
        {
            if(vin[i] == pre[0])
            {
                gen = i;
                break;
            }
        }
        for(int i = 0; i < gen; i++)
        {
            left_vin.push_back(vin[i]);
            left_pre.push_back(pre[i + 1]);
        }
        for(int i = gen + 1; i < lenv; i++)    //这里一开始写成i = gen结果爆内存,没太明白为啥
        {
            right_vin.push_back(vin[i]);
            right_pre.push_back(pre[i]);
        }
        
        head -> left = reConstructBinaryTree(left_pre, left_vin);
        head -> right = reConstructBinaryTree(right_pre, right_vin);
        return head;
    }
};

你可能感兴趣的:(牛客网)