剑指Offer——重建二叉树2

本文介绍了一种根据二叉树的后序遍历和中序遍历结果重建二叉树的方法。通过递归地寻找根节点,并根据根节点划分左右子树,最终完成整个二叉树的重建过程。

Question

输入某二叉树的后序遍历和中序遍历的结果,请重建出该二叉树。假设输入的后序遍历和中序遍历的结果中都不含重复的数字。例如输入后序遍历序列{1, 3, 4, 2}和中序遍历序列{1, 2, 3, 4},则重建二叉树并返回。

Solution

这道题跟中序和先序重建二叉树差不多,不同之处,就在于坐标的开始位置,以及后序遍历的最后一个节点是根节点。

Code

/**
 * 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) {
        if (inorder.size() == 0 || postorder.size() == 0)
            return NULL;
        return ConstructTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
    }
    
    TreeNode* ConstructTree(vector<int>& inorder, vector<int>& postorder, 
            int in_start, int in_end, int post_start, int post_end) {
        int rootValue = postorder[post_end];
        TreeNode* root = new TreeNode(rootValue);
        
        if (in_start == in_end) {
            if (post_start == post_end && inorder[in_start] == postorder[post_start])
                return root;
        }
        
        int rootIn = in_start;
        while (rootIn <= in_end && inorder[rootIn] != rootValue)
            rootIn++;
        
        int leftPostLength = rootIn - in_start;
        if (leftPostLength > 0) {
            // 注意后序开始位置的写法
            root->left = ConstructTree(inorder, postorder, in_start, rootIn - 1, post_start, post_start + leftPostLength - 1);
        }
        if (leftPostLength < in_end - in_start) {
            // 注意后序位置开始的写法
            root->right = ConstructTree(inorder, postorder, rootIn + 1, in_end, post_start + leftPostLength, post_end - 1);
        }
        
        return root;
    }
};

转载于:https://www.cnblogs.com/zhonghuasong/p/7096300.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值