zoukankan      html  css  js  c++  java
  • LeetCode "Construct Binary Tree from Inorder and Postorder Traversal"

    Another textbook problem. We take back of postorder array as the current root, and then we can split the inorder array: 1st half for current right child, and 2nd for current left.

    class Solution {
    public:
        TreeNode *_buildTree(int in[], int i0, int i1, int insize, int post[], int &inx_p)
        {
            if(inx_p < 0 || i0 > i1) return NULL;
    
            TreeNode *pRoot = new TreeNode(post[inx_p]);
    
            int iRoot = std::find(in, in + insize, post[inx_p--]) - in;
            TreeNode *pRight = _buildTree(in, iRoot + 1, i1, insize, post, inx_p);
            pRoot->right = pRight;
            TreeNode *pLeft= _buildTree(in, i0, iRoot-1, insize, post, inx_p);
            pRoot->left = pLeft;
            return pRoot;
        }
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            int *in = new int[inorder.size()];
            std::copy(inorder.begin(), inorder.end(), in);
            int *post = new int[postorder.size()];
            std::copy(postorder.begin(), postorder.end(), post);
            int inx = postorder.size() - 1;
            return _buildTree(in, 0, inorder.size()-1, inorder.size(), post, inx);
        }
    };
  • 相关阅读:
    [循环卷积]总结
    [FFT/NTT/MTT]总结
    [BZOJ 4870] 组合数问题
    [BZOJ 4809] 相逢是问候
    [BZOJ 4591] 超能粒子炮-改
    __getattribute__
    __repr__
    __reduce__
    数据库查询转excel小工具
    Git常用操作
  • 原文地址:https://www.cnblogs.com/tonix/p/3862051.html
Copyright © 2011-2022 走看看