Leetcode典型题解答和分析、归纳和汇总——T106(从后序与中序遍历序列构造二叉树)

本文介绍了一种使用递归方法,通过给定的后序遍历和中序遍历序列来构建二叉树的算法。通过构建hashmap优化查找效率,实现左右子树的边界确定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

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

问题分析:

采用传统的递归方式求解:

class Solution{
    public:
    unordered_map<int, int> in_pos;  //构建构建构建hashmap
    vector<int> post;
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
    {
        int in_len = inorder.size();
        for(int i= 0; i<in_len;i++)
        {
           in_pos[inorder[i]] =i;    
        }
        
        post = postorder;
        
        TreeNode* root = buildTree(0,in_len-1,0,post.size()-1);
        return root;
    }
    
    TreeNode* buildTree(int in_left, int in_right, int post_left,int post_right)
    {
        if(in_left>in_right || post_left>post_right) return NULL;
        
        int root_val = post[post_right];
        int root_pos = in_pos[root_val];
        TreeNode* node = new TreeNode(root_val);
        node->left = buildTree(in_left,root_pos-1,post_left,post_left+root_pos-in_left-1); //左子树上的边界确定
        node->right = buildTree(root_pos+1,in_right,post_left+root_pos-in_left,post_right-1);  //确定右子树的两边界(对于inorder 和postorder遍历来说)
        return node;
    }
    
    };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值