cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/778b74a53665

时间限制:1秒 空间限制:32768K

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

我的代码

/**
 * 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<int> pre,vector<int> vin) {
        //前序遍历:根->左->右;中序遍历:左->根->右
        return reConstructBinaryTreeCore(pre,0,pre.size()-1,vin,0,vin.size()-1);
    }
    TreeNode* reConstructBinaryTreeCore(vector<int> pre, int sPre, int ePre,
                                        vector<int> vin, int sVin, int eVin){
        if(sPre>ePre || sVin>eVin) return nullptr;
        TreeNode* root=new TreeNode(pre[sPre]);
        int i;
        for(i=sVin;i<=eVin;i++)
            if(vin[i]==pre[sPre]){
                root->left=reConstructBinaryTreeCore(pre,sPre+1,sPre+i-sVin,
                                            vin,sVin,i-1);
                root->right=reConstructBinaryTreeCore(pre,sPre+i-sVin+1,ePre,
                                            vin,i+1,eVin);
                break;
            }
        return root;
    }
};

运行时间:6ms
占用内存:748k

posted on 2019-04-27 22:39  cherrychenlee  阅读(62)  评论(0编辑  收藏  举报