【leetcode】Construct Binary Tree from Preorder and Inorder Traversal

#include<iostream>
#include<vector>
#include<map>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int val):val(val),left(NULL),right(NULL){};
};

class Solution1
{
public:
    map<int,int>result;
    void fun(vector<int>pre,vector<int>ino)
    {
        if(pre.empty())
            return;

        for(int i=0;i<ino.size();i++)
            result[ino[i]]=i;
        TreeNode *root;
        root=build(pre,0,pre.size()-1,ino,0,ino.size()-1);
        displaypost(root);
        cout<<endl;
    }
    TreeNode* build(vector<int>pre,int s0,int e0,vector<int>ino,int s1,int e1)
    {
        if(s0>e0||s1>e1)
            return NULL;
        int mid=result[pre[s0]];
        TreeNode* root=new TreeNode(pre[s0]);
        int num=mid-s1;
        root->left=build(pre,s0+1,s0+num,ino,s1,mid-1);
        root->right=build(pre,s0+num+1,e0,ino,mid+1,e1);
        return root;
    }
    void displaypost(TreeNode* root)
    {
        if(!root)
            return;
        displaypost(root->left);
        displaypost(root->right);
        cout<<root->val<<' ';
    }
};

class Solution2
{
public:
    map<int,int>result;
    void fun(vector<int>ino,vector<int>post)
    {
        if(post.empty())
            return ;
        for(int i=0;i<ino.size();i++)
            result[ino[i]]=i;
        TreeNode* root;
        root=build(ino,0,ino.size()-1,post,0,post.size()-1);
        displaypre(root);
        cout<<endl;
    }
    TreeNode* build(vector<int>ino,int s0,int e0,vector<int>post,int s1,int e1)
    {
        if(s0>e0||s1>e1)
            return NULL;
        int mid=result[post[e1]];
        TreeNode* root=new TreeNode(post[e1]);
        int num=mid-s0;
        root->left=build(ino,s0,mid-1,post,s1,s1+num-1);
        root->right=build(ino,mid+1,e0,post,s1+num,e1-1);
        return root;
    }
    void displaypre(TreeNode* root)
    {
        if(!root)
            return;
        cout<<root->val<<' ';
        displaypre(root->left);
        displaypre(root->right);
    }

};

void main()
{
    Solution1 solution1;
    Solution2 solution2;
    int res1[7]={1,2,4,5,6,3,7};
    int res2[7]={4,2,6,5,1,3,7};
    int res3[7]={4,6,5,2,7,3,1};
    vector<int>result1(res1,res1+7);
    vector<int>result2(res2,res2+7);
    vector<int>result3(res3,res3+7);
    solution1.fun(result1,result2);//由前序和中序遍历得到后序遍历
    solution2.fun(result2,result3);//由中序和后序得到前序遍历
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值