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

力扣题目链接(opens new window)

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

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

例如,给出

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

106.从中序与后序遍历序列构造二叉树_第1张图片

class Solution {
public:
    TreeNode* dfs(vector& inorder, vector& postorder){
        if(postorder.size() == 0) return nullptr;
        int tmp = postorder.back();
        TreeNode* root = new TreeNode(tmp);
        if(postorder.size() == 1) return root;
        //确定分割点
        int index;
        for(index = 0;index < inorder.size();index++){
            if(inorder[index] == tmp) break;
        }
        //分割,左右中
        vector leftin(inorder.begin(),inorder.begin()+index);
        vector rightin(inorder.begin()+index+1,inorder.end());

        postorder.resize(postorder.size()-1);
        //左右后
        vectorleftpost(postorder.begin(),postorder.begin()+leftin.size());
        vectorrightpost(postorder.begin()+leftin.size(),postorder.end());
        root->left = dfs(leftin,leftpost);
        root->right = dfs(rightin,rightpost);
        return root;
    }
    TreeNode* buildTree(vector& inorder, vector& postorder) {
        //也可以采用数组下标,来减少空间复杂度。
        if(inorder.size() == 0 || postorder.size() == 0) return nullptr;
        return dfs(inorder,postorder);
    }
};

//维护边界点(动态更新边界)。一般方法,可减少空间复杂度
class Solution {
public:
    TreeNode* dfs(vector& inorder,int inbeg,int inend,vector& postorder,int postbeg,int postend){
        if(postend == postbeg) return nullptr;
        int tmp = postorder[postend-1];
        TreeNode* root = new TreeNode(tmp);
        if(postend - postbeg == 1) return root;

        //分割点
        int index;
        for(index = inbeg;index < inend;index++){
            if(inorder[index] == tmp) break;
        }
        //中
        int leftinbeg = inbeg;
        int leftinend = index;
        int rightinbeg = leftinend+1;
        int rightinend = inend;
        //后
        int leftpostbeg = postbeg;
        int leftpostend = postbeg+leftinend-leftinbeg;
        int rightpostbeg = leftpostend;
        int rightpostend = postend-1;
        root->left = dfs(inorder,leftinbeg,leftinend,postorder,leftpostbeg,leftpostend);
        root->right = dfs(inorder,rightinbeg,rightinend,postorder,rightpostbeg,rightpostend);
        return root;
    }
    TreeNode* buildTree(vector& inorder, vector& postorder) {
        if(inorder.size() == 0 || postorder.size() == 0) return nullptr;
        return dfs(inorder,0,inorder.size(),postorder,0,postorder.size());
    }
};

你可能感兴趣的:(leetcode练习,算法,数据结构,c++)