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);
        }
    };
  • 相关阅读:
    2020软件工程作业05
    2020软件工程作业00--问题清单
    2020软件工程作业03
    2020软件工程作业02
    2020软件工程作业01
    软件工程个人作业06
    软件工程作业04
    软件工程作业05
    软件工称作业03
    2020软件工程作业02
  • 原文地址:https://www.cnblogs.com/tonix/p/3862051.html
Copyright © 2011-2022 走看看