剑指offer-7、重建二叉树

题目描述

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

思路:

对于前序遍历的区域R1,中序遍历区域R2,想办法将其分为左右区域,划分的方法为:

1、前序遍历先遍历根节点,所以R1的第0个元素rootValue为根节点

2、中序遍历先遍历左子树,后访问根节点,所以找到rootValue节点的相对位置index,该位置之前的节点都是左子树

3、现在可以确定:

      根节点:R1[0]

      左子树的先序遍历:R1[1,...index]

     右子树的先序遍历:R1[index+1, .......]

    左子树的中序遍历:R2[0, .....index-1]

    右子树的中序遍历:R2[index+1,......]

class Solution {
public:
    TreeNode* reConstructBinaryTreeCore(vector<int> &pre, int s1, int e1, vector<int> &vin, int s2, int e2)
    {
        
        if(s1>e1)
        {
            return NULL;
        }
        
        TreeNode *pNode = new TreeNode(pre[s1]);
        
        //从vin中找到等于pre[s1]的位置index,肯定可以找到
        int index = 0;
        while(vin[s2+index] != pre[s1])
        {
            index++;
        }
        
        //根据切分点index继续切分左右子树
        pNode->left = reConstructBinaryTreeCore(pre, s1+1, s1+index, vin, s2, s2+index-1);
        pNode->right = reConstructBinaryTreeCore(pre, s1+index+1, e1, vin, s2+index+1, e2);
        
        return pNode;
    }
    
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        TreeNode *pNode = NULL;
        
        pNode = reConstructBinaryTreeCore(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
        
        return pNode;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值