中/后序遍历序列重建二叉树

Construct Binary Tree from Inorder and Postorder Traversal
题意:输入某二叉树的中序遍历和后序遍历的结果,请重建出该二叉树。

解题思路:取出后序遍历序列最后一个结点的值,即根结点的值
在中序遍历序列中找出根结点的位置,计算distance(in_first, in_left_last)为len
则post_left_last = next(post_first, len)
中序遍历序列中对应的左子树的中序遍历序列为in_first, in_left_last
后序遍历序列中对应的左子树的后序遍历序列为post_first, post_left_last
中序遍历序列中对应的右子树的中序遍历序列为next(in_left_last), in_last
后序遍历序列中对应的右子树的后序遍历序列为post_left_last, prev(post_last)
然后递归处理

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return buildTree(begin(inorder), end(inorder), begin(postorder), end(postorder));
    }

    template<typename MyIt>
    TreeNode* buildTree(MyIt in_first, MyIt in_last, MyIt post_first, MyIt post_last) {
        if (in_first == in_last)
            return nullptr;
        if (post_first == post_last)
            return nullptr;

        const int rootValue = *prev(post_last);
        auto in_left_last = find(in_first, in_last, rootValue);
        int len = distance(in_first, in_left_last);
        auto post_left_last = next(post_first, len);

        TreeNode *root = new TreeNode(rootValue);
        root->left = buildTree(in_first, in_left_last, post_first, post_left_last);
        root->right = buildTree(next(in_left_last), in_last, post_left_last, prev(post_last));

        return root;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值