【面试题】重建二叉树(解题思路分析+Java、Python实现+代码详细注释)

题目描述

在这里插入图片描述

解题思路

  1. 在⼆叉树的前序遍历序列中, 第⼀个数字即为树的根结点 root的值。
  2. 扫描中序遍历序列,找到根节点 root在中序遍历中的位置,从而将中序遍历序列划分为 [ 左子树 | 根节点 | 右子树 ]。 为了提升搜索效率,使用哈希表 预存储中序遍历的值与索引的映射关系,将每次查找的时间复杂度降为 O(1)。
  3. 根据中序遍历中的左(右)子树的节点数量,可将前序遍历划分为 [ 根节点 | 左子树 | 右子树 ] 。

这样一来,我们已经分别找到了左、 右子树的前序遍历序列和中序遍历序列, 我们可以用同样的方法分别再去构建左、右子树。 也就是说, 接下来的事情可以用递归的方法去完成。

时间复杂度:O(n),初始化 HashMap 需遍历 inorder ,占用 O(n) ;递归共建立 n 个节点,每层递归中的节点建立、搜索操作占用 O(1),因此递归占用 O(n) 。
空间复杂度:O(n),HashMap 和递归调用栈共需要 O(n) 的额外空间

Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if len(preorder) == 0 or len(inorder) == 0: # 二叉树为空
            return None
        self.pre_list = preorder
        
        # 为了提高查找的效率,使用哈希表预存储中序遍历的节点值与索引的映射关系
        self.dic = {}
        for i in range(len(inorder)):
            self.dic[inorder[i]] = i
            
        # 调用递归函数,参数为前序遍历中根节点的索引pre_root_index、中序遍历左边界in_left、中序遍历右边界in_right    
        return self.recur(0, 0, len(inorder)-1)
        
    def recur(self, pre_root_index, in_left, in_right):
        # 递归终止条件,当前子树的中序遍历为空,说明已经越过了叶子节点
        if in_left > in_right: return 
        
        # 建立当前子树的根节点 root
        root = TreeNode(self.pre_list[pre_root_index]) 
        
        # 查找根节点在中序遍历中的索引,从而划分子树为[ 左子树 | 根节点 | 右子树 ]
        in_root_index = self.dic[root.val] 
        
        # 开启下一层递归,构建 root的左子树和右子树
        root.left = self.recur(pre_root_index+1, in_left, in_root_index-1) 
        # 右子树根节点在前序中的索引= 当前根节点的前序索引+(当前根节点的中序索引-中序左边界+1),其中括号内=左子树长度。
        root.right = self.recur(pre_root_index+(in_root_index-in_left+1), in_root_index+1, in_right)
        
        # 返回当前递归层级建立的根节点 root 为上一递归层级的根节点的左或右子节点
        return root 

另一种写法

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        def recur(pre_root_index, in_left, in_right):
            if in_left > in_right: return # 递归终止条件
            root = TreeNode(preorder[pre_root_index]) # 建立当前子树的根节点
            in_root_index = inorder.index(root.val) # 获取根节点在中序遍历序列中的位置,使用index()查找的时间复杂度为 O(N) ,用字典则是 O(1)
            root.left = recur(pre_root_index+1, in_left, in_root_index-1) # 构建左子树
            root.right = recur(pre_root_index + (in_root_index - in_left + 1), in_root_index+1, in_right) # 构建右子树
            return root

        if len(preorder) == 0 or len(inorder) == 0: # 二叉树为空
            return None
        return recur(0, 0, len(inorder)-1) # 调用递归函数

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    // 为了提高查找的效率,申请一个哈希表
    HashMap<Integer, Integer> dic = new HashMap<Integer, Integer> ();
    int[] pre_list;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0 || inorder.length == 0) // 二叉树为空
            return null;
        pre_list = preorder;
        // 哈希表存储中序遍历的节点值与索引的映射关系
        for (int i=0; i<inorder.length; i++){
            dic.put(inorder[i],i);
        }
        // 调用递归函数,参数为前序遍历中根节点的索引pre_root_index、中序遍历左边界in_left、中序遍历右边界in_right
        return recur(0,0,inorder.length-1);
    }
    
    // 定义递归函数
    public TreeNode recur(int pre_root_index, int in_left, int in_right){
        if (in_left > in_right) return null; // 递归终止条件
        TreeNode root = new TreeNode(pre_list[pre_root_index]); // 建立当前子树的根节点
        int in_root_index = dic.get(root.val); // 获取根节点在中序遍历序列中的位置
        root.left = recur(pre_root_index+1, in_left, in_root_index-1); // 递归构建左子树
        root.right = recur(pre_root_index+(in_root_index-in_left+1), in_root_index+1, in_right); // 递归构建右子树
        return root; // 返回当前递归层级建立的根节点 root 为上一递归层级的根节点的左或右子节点
    }
}

参考

https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-di-gui-fa-qin/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值