剑指 Offer 07. 重建二叉树

剑指 Offer 07. 重建二叉树

输入二叉树的前序和中序遍历,重建二叉树。假设输入的前序遍历和中序遍历都不包含重复的数字。

例如:

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回的二叉树:
  	3
   / \
  9  20
    /  \
   15   7
  • 前序遍历的第一个元素为树的根节点 node 的值;
  • 在中序遍历中搜索根节点 node 的索引,可将中序遍历划分为[左子树|根节点|右子树]。
  • 根据中序遍历中的左右子树的节点数量,可将前序遍历划分为[根节点|左子树|右子树]。

采用分治算法:

  • 建立根节点 node:节点值为 preorder[root]。

  • 划分左右子树:查找根节点在中序遍历中的索引i;

  • 构建左右子树,开启左右子树递归:

    根节点索引中序遍历左边界中序遍历右边界
    左子树(root+1)lefti-1
    右子树(根节点索引+左子树长度+1)(root+i-left+1)i+1right

代码:

class Solution {
private:
    vector<int>preorder;
    unordered_map<int,int>dic;
    TreeNode* recur(int root,int left,int right){
        if(left>right)
            return nullptr;
        TreeNode *node=new TreeNode(preorder[root]);
        int i=dic[preorder[root]];
        node->left=recur(root+1,left,i-1);
        node->right=recuir(root+i-left+1,i+1,right);
        return node;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
		this->preorder=preorder;
		for(int i=0;i<inorder.size();i++)
        {
            dic[inorder[i]]=i;
        }
        return recur(0,0,inorder.size()-1);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值