LeetCode-Notes
  • Introduction
  • Records of Practice
  • 关于Github 不支持密码问题
  • 面试题
    • 搜索广告
    • 多模态大模型
    • 刷题记录
  • 算法代码实现
  • Python
    • Python 笔记
  • Spark
    • PySpark
    • Spark Issues
    • Spark调优笔记
  • FeatureEngineering
    • Feature Cleaning
    • Feature Selection
    • Feature Transformation
    • Feature Crossing
  • Recommendation Algorithm
    • Recall-and-PreRank
      • Non-Negative Matrix Fatorization(NMF)
      • Fatorization Machine(FM)
      • User-base/Item-base实现
      • 多路召回实现
    • Ranking
      • NeuralFM
      • DeepFM
      • Deep&Cross network (DCN)
    • DeepLearning-Basic
      • Attention
      • Dropout
      • Batch Norm
  • Machine Learning
    • XGBoost
    • Cross Entropy Loss
    • Other models
  • Graph Neural Network
    • GNN-1-Basic
  • Big Data
    • Reservoir Sampling
  • SQL
    • SQL and PySpark functions
    • Query Film Infomation
    • Create, Insert and Alter Actor Table
    • Manage Employment Data
    • Manage Employment Data -2
  • DataStructure
    • Searching
      • Find power
      • 2 Sum All Pair II
      • Two Sum
      • Search in Rotate Array
      • Search In Shifted Sorted Array II
      • Search in 2D array
      • Three Sum with duplicated values
      • Median of Two Sorted Arrays
    • Array
      • Longest Consecutive Subarray
      • Merge Two Array in-place
      • Trapping water
      • Rotate matrix
    • Sorting
      • Merge intervals
      • 排序
      • 最小的k个数
      • Find TopK largest- QuickSelect快速选择 method
      • MergeSort Linkedlist
      • 第K大元素
    • LinkedList
      • Reverse LinkedList I
      • Reverse K-group linked list
      • Detect Start of Cycle
      • HasCycle
      • DetectCycle II
      • 链表的共同节点
      • 链表中倒数第k个节点
      • 删除链表倒数第k个节点
      • 合并两个链表
      • 在排序数组中查找元素的第一个和最后一个位置
      • 删除链表里面重复的元素-1
    • Tree
      • Find Tree height (general iteration method)
      • Check BST and Check CompleteTree
      • ZigZag Order traversal
      • Binary Tree diameter I
      • Maximum Path Sum Binary Tree
      • Maximum Path Sum Binary Tree II
      • Binary Tree Path Sum To Target III
      • Tree diameter 树的直径II
      • Tree ReConstruction
      • Check if B is Subtree of A
      • The Kth smallest in Binary Search Tree
      • 打印Tree的右视图
      • 二叉搜索树的后序遍历序列
      • 重建二叉树
      • 判断二叉树是否对称
      • Path Sum to Target in Binary Tree
      • Tree-PreOrder-InOrder-PostOrder
    • Heap&Queue
      • Top-K smallest
      • 滑动窗口最大值
      • Find the K-Largest
    • 合并k个已排序的链表
    • String
      • Reverse String
      • 最长不含重复字符的子字符串
      • 最长回文串
      • 最长回文子序列-DP
    • DFS/BFS
      • Number of island
      • Number of Provinces
      • All Permutations of Subsets without duplication
      • All Permutations of Subsets with duplication
      • Combinations Of Coins
      • All Subset I (without fixing size of subset, without order, without duplication)
      • All Subset of K size without duplication II
      • All Subset of K size III (with duplication without considering order)
      • All Permutation II (with duplication and consider order)
      • Factor Combination-质数分解
    • DynamicProgramming
      • DP-解题过程
      • Find Continuous Sequence Sum to Target
      • 1800. Maximum Ascending Subarray Sum
      • NC91 最长上升子序列
      • 查找string的编码方式个数
      • Maximum Product
      • Longest Common Substring
      • Longest Common Substring-II
      • minEditCost
      • Backpack I
      • Array Hopper I
      • Minimum distance between strings
      • 最大正方形
  • Big Data Algorithms
    • Big Data Processing Algorithms
      • Reservior Sampling
      • Shuffle
      • MapReduce
      • Bloom Filter
      • BitMap
      • Heap For Big Data
Powered by GitBook
On this page
  • 1. Link
  • 2. 题目描述
  • 输入
  • 返回值
  • 3.思路
  • 4. Coding

Was this helpful?

  1. DataStructure
  2. Tree

Tree ReConstruction

PreviousTree diameter 树的直径IINextCheck if B is Subtree of A

Last updated 4 years ago

Was this helpful?

1. Link

2. 题目描述

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

输入

复制

[1,2,3,4,5,6,7],[3,2,4,1,6,5,7]

返回值

复制

{1,2,5,3,4,6,7}

3.思路

  1. Recursion: pre-order 用于遍历每一个node,并得到当前的subtree的rootnode,(pre-order从左往右数起,第一个node是root node) in-order 用于搜索root node位置来重建树

  2. Recursion: 输入是 剩下没有重建的pre-order的node和in-order 的信息,以及搜索的左右边界缩小搜索范围

  3. 如果在left, right边界里面找到root后,以它为中心分开左右两个subarray查找左右subtree的rootnode,并接到当前的rootnode的left, right

  4. Time: O(n) for searching root in subarray, O(n) for iterating every node for reconstruction, so O(n^2)

  5. Space: O(logn) for recursion

4. Coding

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        # 1. for pre-order, the first node = root, for in-order
        #    it can be used for binary search to reconstruct node
        # 2. idea: recursion
        #    input: in-order, pre-order array, position of node in pre-order left, right boundary to
        #    output: root node of subtree
        #    base case: if left boundary >= right boundary and right != node
        #     return None
        #    1. find the node of pre-order in in-order 
        #    2. split in-order array into left, right arrays based on 
        #        root node
        #    3. search the second node of pre-order in left and right array of in-order
        #    4. connect root node with root of left-subtree and root of right subtree
        #    5. return root node
        #
        #
        # test case:[1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
        # Time: O(n) for finding root in in-order, O(n) for iterate every node
        #  in tree, so O(n^2)
        # Space: O(logn) for recursion
        #
        if not pre or not tin or len(pre)!= len(tin):
            return None
        
        root = self.findroot(pre, tin,  0, len(tin)-1)
        return root
    
    def findroot(self,pre, tin, left, right ):
        if left >=right :
            if pre and pre[0] == tin[right]:
                return TreeNode(pre.pop(0))
            return None
        # find root node
        idx = None
        for i in range(left, right+1):
            if tin[i] == pre[0]:
                idx = i
                break
        if idx == None:
            return None
        p_node = TreeNode(pre.pop(0))
        # search left array
        l_node = self.findroot(pre, tin, left, idx-1 )
        r_node = self.findroot(pre, tin,  idx+1, right )
        
        p_node .left = l_node
        p_node.right = r_node
        return p_node
        

重建二叉树_牛客题霸_牛客网
Logo