LeetCode106—Construct Binary Tree from Inorder and Postorder Traversal

本文详细介绍了如何通过后序和中序遍历序列构建二叉树,采用递归方法实现,重点突出算法逻辑与实现细节。

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

LeetCode106—Construct Binary Tree from Inorder and Postorder Traversal

原题

Given inorder and postorder traversal of a tree, construct the binary tree.

后序遍历和中序遍历建立数

分析

LeetCode—105类似,后序遍历从后往前,要先递归右子树再递归左子树。

代码

class Solution {
private:
    TreeNode* helper(vector<int>&inorder, vector<int>&postorder, map<int, int>&index,int pstart,int pend,int instart,int inend)
    {
        if (instart > inend)
            return NULL;
        int rootval = postorder[pend];
        int rootindex = index[rootval];
        TreeNode*root = new TreeNode(rootval);
        root->right = helper(inorder, postorder, index, pend-inend+rootindex, pend - 1, rootindex + 1, inend);
        root->left = helper(inorder, postorder, index, pstart, pend - inend + rootindex-1, instart,rootindex-1);
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        map<int, int>index;
        for (int i = 0; i < inorder.size(); i++)
        {
            index[inorder[i]] = i;
        }
        return helper(inorder, postorder, index, 0, postorder.size() - 1, 0, inorder.size() - 1);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值