剑指 Offer 07. 重建二叉树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

class Solution {
    int[] preorder;
    HashMap<Integer, Integer> map = new HashMap<>();
    // 前序遍历 preorder: 根 -- 左 -- 右   第一个肯定是根节点
    // 中序遍历 inorder: 左 -- 根 -- 右
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        return rebuild(0, 0, inorder.length - 1);  
    }

    // pre_root_index : 根节点 在 前序遍历中的下标
    // in_left_index: 这棵树在中序遍历中的左边界
    // in_right_index: 这棵树在中序遍历中的右边界
    public TreeNode rebuild(int pre_root_index, int in_left_index, int in_right_index){
       if(in_left_index > in_right_index)  return null;
       // 根节点在中序遍历中的位置:in_root_index
       int in_root_index = map.get(preorder[pre_root_index]);
       // 创建一个根节点
       TreeNode node = new TreeNode(preorder[pre_root_index]);
       // 寻找node的左节点: 
       // 在前序遍历中的位置就是  根节点的下标 + 1(右边一个单位)
       // 在中序遍历中的位置就是: 1. 左边界不变,2. 右边界就是根节点的左边一个单位 in_root_index - 1
       node.left = rebuild(pre_root_index + 1, in_left_index, in_root_index - 1);
       // 寻找node的右节点: 
       // 在前序遍历中的位置就是  根节点的下标 + 左子树长度 + 1
       // 在中序遍历中的位置就是: 1. 左边界在根节点的右边一个单位  in_root_index + 1, 2. 右边界不变
       node.right = rebuild(pre_root_index + in_root_index - in_left_index + 1, in_root_index + 1, in_right_index);
       return node;
    }
}

作者:ollieq
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/jian-dan-li-jie-di-gui-zhong-jian-er-cha-ursl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值