LeetCode题解: Construct Binary Tree from Inorder and Postorder Traversal

本文介绍了一种根据给定的中序和后序遍历序列来重建二叉树的方法。通过确定根节点,并递归地构建左子树和右子树,最终还原出完整的二叉树结构。

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

Construct Binary Tree from Inorder and Postorder Traversal

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

Note:
You may assume that duplicates do not exist in the tree.

思路:

已知中序遍历和后序遍历的结果,要求反推树结构。首先注意到后序遍历中,最后一个元素必然是树的根结点。因为树的值没有重复,所以可以在中序遍历中寻找对应的值,这个值左右部分分别是根结点的左子树和右子树,从而知道左右子树元素的个数和中序遍历的结果。再反过来,因为后序遍历首先遍历左子树,再遍历右子树,所以同样可以得到后序遍历的结果。递归构造即可得到原始树结构。

题解:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(const vector<int>& inorder, int is, int ie,
                        const vector<int>& postorder, int ps, int pe)
    {
        if (is > ie)
            return nullptr;
        
        int base = postorder[pe];
        TreeNode* node = new TreeNode(base);
        
        int ipos = is;
        while(inorder[ipos] != base) ++ipos;
        
        int left_nodes = ipos - is;
        int right_nodes = ie - ipos;
        
        if (left_nodes != 0)
            node->left = buildTree(inorder, is, is + left_nodes - 1,
                                   postorder, ps, ps + left_nodes - 1);
        
        if (right_nodes != 0)
            node->right = buildTree(inorder, ipos + 1, ie,
                                   postorder, ps + left_nodes, pe - 1);
                               
        return node;
    }

    TreeNode *buildTree(const vector<int> &inorder, const vector<int> &postorder) {
        if (inorder.empty())
            return nullptr;
            
        return buildTree(inorder, 0, inorder.size() - 1,
                         postorder, 0, postorder.size() - 1);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值