Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

class Solution {
public:
    void f(vector<int> &inorder,int s1, int e1,vector<int> & postorder,int s2, int e2, TreeNode *& root){
        if (s1 > e1){
            return;
        }
        if (!root){
            root = new TreeNode(postorder[e2]);
            int m = s1;
            for(;m <= e1;m++){
                if (inorder[m] == postorder[e2]){
                    break;
                }
            }
            f(inorder,s1,m-1,postorder,s2,s2 + m - s1 - 1,root->left);
            f(inorder,m+1,e1,postorder,e2 - 1 - e1 + (m + 1) ,e2 - 1,root->right);
        }
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!inorder.size()){
            return NULL;
        }
        TreeNode * root = NULL;
        f(inorder,0,inorder.size() -1,postorder,0,postorder.size() -1,root);
        return root;
    }
};

原文链接: https://www.cnblogs.com/kwill/p/3166100.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/94277

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午2:33
下一篇 2023年2月10日 上午2:33

相关推荐