力扣-106题 从中序与后序遍历序列构造二叉树(C++)- dfs

题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题目如下:
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        //中序(左根右)  后序(左右根)
        if(inorder.size()==0||postorder.size()==0) return nullptr;
        //6个参数分别为,中序-中开始-中末尾,后序-后开始-后末尾
        return dfs(inorder,0,inorder.size(),postorder,0,postorder.size());
    }
    TreeNode* dfs(vector<int>& in,int inBegin,int inEnd,vector<int>& post,int postBegin,int postEnd){
        //1、后序
        if(postBegin==postEnd) return nullptr;//空节点

        int rootval=post[postEnd-1];
        TreeNode* root=new TreeNode(rootval);

        if(postEnd-postBegin==1) return root;//只有一个节点

        //2、中序
        int index;
        for(index=inBegin;index<inEnd;index++){
            if(in[index]==rootval) break;//找到后序节点对应在中序中所在的位置
        }

        //3、分割
        //后序
        int leftpostBegin=postBegin;
        int leftpostEnd=postBegin+index-inBegin;
        int rightpostBegin=postBegin+(index-inBegin);
        int rightpostEnd=postEnd-1;
        //中序
        int leftinBegin=inBegin;
        int leftinEnd=index;
        int rightinBegin=index+1;
        int rightinEnd=inEnd;

        root->left=dfs(in,leftinBegin,leftinEnd,post,leftpostBegin,leftpostEnd);
        root->right=dfs(in,rightinBegin,rightinEnd,post,rightpostBegin,rightpostEnd);

        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值