当前位置:网站首页>leetcode:105. Constructing binary trees from preorder and inorder traversal sequences
leetcode:105. Constructing binary trees from preorder and inorder traversal sequences
2022-07-07 07:39:00 【uncle_ ll】
105. Construction of binary trees from traversal sequences of preorder and middle order
source : Power button (LeetCode)
link : https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Given two arrays of integers preorder and inorder , among preorder Is the prior traversal of a binary tree , inorder Is the middle order traversal of the same tree , Please construct a binary tree and return its root node .
Example 1:
Input : preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output : [3,9,20,null,null,15,7]
Example 2:
Input : preorder = [-1], inorder = [-1]
Output : [-1]
Tips :
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder and inorder all No repetition Elements
- inorder All appear in preorder
- preorder Guarantee It is the preorder traversal sequence of binary tree
- inorder Guarantee It is the middle order traversal sequence of binary tree
solution
- recursive : Pre order traversal and middle order traversal are given , The first element of the preorder traversal is the root node location , Then, based on the value of the root node, go to the middle order traversal to find the location of the root node , Based on this, the middle order traversal is divided into left subtree traversal and right subtree traversal results ; Find the preorder traversal of left and right subtrees in the preorder traversal based on the length of left subtree ; Next, you can recursively traverse the pre order and middle order of the left subtree , Preorder traversal and inorder traversal of right subtree ; obtain root.left And root.right, Eventually return root that will do ; The key is to find root The subscript ; If using index Way to find words , Each search requires a traversal , The complexity is O ( n ) O(n) O(n), The total complexity is O ( n 2 ) O(n^2) O(n2), Here, a hash table is used to store the subscript of the middle order traversal , Find time changed to O ( 1 ) O(1) O(1), Space for time
Code implementation
recursive
python Realization
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
n = len(preorder)
if n == 0:
return None
indexs = {
element: i for i, element in enumerate(inorder)}
def helper(preorder_left, preorder_right, inorder_left, inorder_right):
if preorder_left > preorder_right:
return None
preorder_index = preorder_left
inorder_root = indexs[preorder[preorder_index]]
root = TreeNode(preorder[preorder_index])
left_preorder_size = inorder_root - inorder_left
root.left = helper(1+preorder_left, preorder_left+left_preorder_size, inorder_left, inorder_root-1)
root.right = helper(1+preorder_left+left_preorder_size, preorder_right, inorder_root+1, inorder_right)
return root
return helper(0, n-1, 0, n-1)
c++ Realization
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
private:
unordered_map<int, int> index;
public:
TreeNode* helper(const vector<int>& preorder, const vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
if (preorder_left > preorder_right)
return nullptr;
int preorder_root = preorder_left;
int inorder_root = index[preorder[preorder_root]];
TreeNode* root = new TreeNode(preorder[preorder_root]);
int size_left_subtree = inorder_root - inorder_left;
root->left = helper(preorder, inorder, preorder_left+1, preorder_left+size_left_subtree, inorder_left, inorder_root-1);
root->right = helper(preorder, inorder, preorder_left+size_left_subtree+1, preorder_right, inorder_root+1, inorder_right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
if (n == 0)
return nullptr;
for (int i=0; i<n; i++) {
index[inorder[i]] = i;
}
return helper(preorder, inorder, 0, n-1, 0, n-1);
}
};
Complexity analysis
- Time complexity : O ( N ) O(N) O(N)
- Spatial complexity : O ( N ) O(N) O(N)
边栏推荐
- Bindingexception exception (error reporting) processing
- Blue Bridge Cup Netizen age (violence)
- 計算機服務中缺失MySQL服務
- After 95, Alibaba P7 published the payroll: it's really fragrant to make up this
- Outsourcing for three years, abandoned
- 抽絲剝繭C語言(高階)指針的進階
- 1、 Go knowledge check and remedy + practical course notes youth training camp notes
- Outsourcing for four years, abandoned
- Sqlmap tutorial (IV) practical skills three: bypass the firewall
- vus. Precautions for SSR requesting data in asyndata function
猜你喜欢
考研失败,卷不进大厂,感觉没戏了
Advanced practice of C language (high level) pointer
机器人技术创新与实践旧版本大纲
抽絲剝繭C語言(高階)數據的儲存+練習
Simple example of ros2 planning system plansys2
测试周期被压缩?教你9个方法去应对
面试官:你都了解哪些开发模型?
07_ Handout on the essence and practical skills of text measurement and geometric transformation
MIPS uclibc cross compile ffmpeg, support g711a encoding and decoding
A concurrent rule verification implementation
随机推荐
Implementing data dictionary with JSP custom tag
Mutual conversion between InputStream, int, shot, long and byte arrays
微信小程序中的路由跳转
How do I get the last part of a string- How to get the last part of a string?
Leetcode-226. Invert Binary Tree
JS decorator @decorator learning notes
抽丝剥茧C语言(高阶)指针进阶练习
Model application of time series analysis - stock price prediction
按键精灵脚本学习-关于天猫抢红包
mips uclibc 交叉编译ffmpeg,支持 G711A 编解码
抽丝剥茧C语言(高阶)数据的储存+练习
How to reduce inventory with high concurrency on the Internet
身边35岁程序员如何建立起技术护城河?
Detailed explanation of neo4j installation process
Advanced practice of C language (high level) pointer
Differences between H5 architecture and native architecture
L'étape avancée du pointeur de langage C (haut de gamme) pour l'enroulement des cocons
Mobx knowledge point collection case (quick start)
ASEMI整流桥RS210参数,RS210规格,RS210封装
Dynamics CRM server deployment - restore database prompt: the database is in use