LeetCode刷题笔记 106. 从中序与后序遍历序列构造二叉树

106. 从中序与后序遍历序列构造二叉树

题目要求

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

题解

https://github.com/soulmachine/leetcode

和上题相比主要是换了个根节点的位置。

class Solution {
public:
    template<typename T>
    TreeNode* buildTree(T infirst,T inlast,T postfirst,T postlast){
        if(infirst==inlast) return nullptr;
        if(postfirst==postlast) return nullptr;

        const auto val=*prev(postlast);
        TreeNode *root=new TreeNode(val);

        auto inRootPos=find(infirst,inlast,val);
        auto leftSize=distance(infirst,inRootPos);
        auto postLeftLast=next(postfirst,leftSize);

        root->left=buildTree(infirst,inRootPos,postfirst,postLeftLast);
        // inRootPos 是inorder root的位置  postlast 是postroot的位置
        root->right=buildTree(next(inRootPos),inlast,postLeftLast,prev(postlast));
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return buildTree(begin(inorder),end(inorder),begin(postorder),end(postorder));
    }
};
发布了18 篇原创文章 · 获赞 0 · 访问量 1780

猜你喜欢

转载自blog.csdn.net/g534441921/article/details/104240606