(C++)剑指offer-4:重建二叉树(yshennp)

剑指offer-4:重建二叉树

给定:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]
返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
在这里插入图片描述
返回的二叉树序列如下所示:

	     3
	    /  \
	  9    20
	      /   \
	    15     7 

前序遍历(根左右)3-9-20-15-7
中序遍历(左根右)9-3-15-20-7

处理思想:递归,时间复杂度O(n)
1.利用前序遍历寻找根节点,遍历的第一个数即为根节点的值;
2.在中序遍历中找到根节点的位置k,则k左边是左子树的中序遍历,右边是右子树的中序遍历;
3.如果左子树的中序遍历长度为l,则在前序遍历中,根节点之后的l个数即为左子树的前序遍历,剩下的即为右子树的前序遍历;
4.得到左右子树的前中序遍历后,即可以递归创建左右子树,再创建根节点;

由于用哈希表记录每个值在中序遍历中的位置,因此在中序遍历中查找根节点的位置只需要O(1)的时间,创建每个节点需要的时间为O(1),总体时间复杂度为O(n)

代码如下:

class Solution {
public:
    unordered_map<int, int> pos;
    TreeNode* reConstructBinaryTree(vector<int>& preorder,vector<int>& inorder) {
        int n = preorder.size();
        for(int i = 0; i < n; i++){
            pos[inorder[i]] = i; //opps
        }
        return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
    }
    
    TreeNode* dfs(vector<int>& pre, vector<int>& in, int pl, int pr, int il, int ir){
        if(pl > pr) return nullptr;
        int k =  pos[pre[pl]] - il;
        TreeNode* root = new TreeNode(pre[pl]);
        root->left = dfs(pre, in, pl + 1 , pl + k, il, il + k - 1); //opps
        root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir); //opps
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值