zoukankan      html  css  js  c++  java
  • leetcode第一刷_Construct Binary Tree from Inorder and Postorder Traversal

    这道题是为数不多的感觉在读本科的时候见过的问题。

    人工构造的过程是如何呢。兴许遍历最后一个节点一定是整棵树的根节点。从中序遍历中查找到这个元素,就能够把树分为两颗子树,这个元素左側的递归构造左子树,右側的递归构造右子树。元素本身分配空间,作为根节点。

    于set和map容器不同的是。vector容器不含find的成员函数。应该用stl的库函数,好在返回的也是迭代器,而vector的迭代器之间是能够做减法的。偏移量非常方便的得到。

    TreeNode *buildRec(vector<int> &inorder, int si, vector<int> &postorder, int so, int len){
        if(len <= 0)    return NULL;
        TreeNode *root = new TreeNode(postorder[so]);
        int index = find(inorder.begin(), inorder.end(), postorder[so]) - inorder.begin();
        int newlen = index - si;
        root->left = buildRec(inorder, si, postorder, so-len+newlen, newlen);
        root->right = buildRec(inorder, index+1, postorder, so-1, len-newlen-1);
        return root;
    }
    
     
     
    class Solution {
    public:
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            return buildRec(inorder, 0, postorder, inorder.size()-1, inorder.size());
        }
    };


  • 相关阅读:
    哈夫曼编码-C语言实现
    KMP和BF算法-C语言实现
    Spring框架(1)--只是入门
    MyBatis(1)
    antd TreeSelect 无限级选择
    download下载文件
    react搭建项目问题
    js 数组转tree结构
    反映复制到剪贴板(npm安装)
    js前端实现Table导出excel表格
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5135053.html
Copyright © 2011-2022 走看看