zoukankan      html  css  js  c++  java
  • 重建二叉树

    原文地址: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

  • 相关阅读:
    新一轮人工智能的兴起引发的思考
    企业应用架构的发展演进
    利用poi插件,把Excel内容读入Java,把Java中的内容输出到Exce
    mysql免安装被指
    正则表达式大全
    开发数据库步骤
    JVM
    Java面试题一
    java集合总结
    JAVA WEB回顾一
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10780860.html
Copyright © 2011-2022 走看看