当前位置:网站首页>[leetcode] construct a binary tree by traversing the sequence from front to middle (continuous optimization)
[leetcode] construct a binary tree by traversing the sequence from front to middle (continuous optimization)
2022-06-11 01:50:00 【xiaoshijiu333】
#LeetCode A daily topic 【 Special topic of binary tree 】
- Construction of binary trees from traversal sequences of preorder and middle order
https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ - analysis
Before the order : root —— Left —— Right
Middle preface : Left —— root —— Right
The first element of the preamble must be the root node , In the middle order , The element on the left of the root node is all the elements of the left subtree , The elements on the right of the root node are all the elements of the right subtree , Find the left subtree in the preordered sequence 、 The preorder sequence of the right subtree , In the recursive processing of the left and right subtrees - Realization
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) {
return null;
}
int rootValue = preorder[0], len = preorder.length;
if (len == 1) {
return new TreeNode(rootValue);
}
// Find Zuozi tree 、 Middle order of right subtree
int location = 0;
for (int i = 0; i < len; i++) {
if (inorder[i] == rootValue) {
location = i;
break;
}
}
int[] leftInorder = new int[location];
int[] rightInorder = new int[len - location - 1];
System.arraycopy(inorder, 0, leftInorder, 0, location);
System.arraycopy(inorder, location + 1, rightInorder, 0, rightInorder.length);
// Find the first order of the left subtree 、 Preorder of right subtree
int[] leftPreorder = new int[location];
int[] rightPreorder = new int[rightInorder.length];
System.arraycopy(preorder, 1, leftPreorder, 0, leftPreorder.length);
System.arraycopy(preorder, 1 + leftPreorder.length, rightPreorder, 0, rightPreorder.length);
TreeNode left = buildTree(leftPreorder, leftInorder);
TreeNode right = buildTree(rightPreorder, rightInorder);
return new TreeNode(rootValue, left, right);
}
A large number of arrays are used copy
LeetCode Time consuming :6ms
- Optimize
Involving from the original array copy A new array for recursive processing , You can use the subscript of an array instead of , Start subscript 、 The end subscript indicates the range of an array .
public TreeNode buildTreeOptimize(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0) {
return null;
}
return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
}
private TreeNode buildTree(int[] preorder, int[] inorder, int preorderStart, int preorderEnd,
int inorderStart, int inorderEnd) {
// Recursion end condition
if (preorderStart > preorderEnd) {
return null;
}
// The first element of the preorder is the root node
int rootValue = preorder[preorderStart];
// The position of the root node in the middle order
int rootLocation = getIndexFromArray(rootValue, inorder, inorderStart, inorderEnd);
// Number of left subtree nodes 、 Length of the preorder array
int leftLength = rootLocation - inorderStart;
// Find the left and right subtrees and start with the middle order 、 Ending subscript
TreeNode left = buildTree(preorder, inorder, preorderStart + 1, preorderStart + leftLength,
inorderStart, rootLocation - 1);
TreeNode right = buildTree(preorder, inorder, preorderStart + leftLength + 1, preorderEnd,
rootLocation + 1, inorderEnd);
return new TreeNode(rootValue, left, right);
}
private int getIndexFromArray(int rootValue, int[] inorder, int inorderStart, int inorderEnd) {
for (int i = inorderStart; i <= inorderEnd; i++) {
if (inorder[i] == rootValue) {
return i;
}
}
return -1;
}
LeetCode Time consuming :3ms
- Optimizing
Read the explanation of the question , The result of the middle order traversal is first represented by a map Store it , It is convenient to quickly retrieve the subscript according to the value each time , Space for time
Map<Integer, Integer> map = new HashMap<>();
// The idea is right , Find the first order of the left subtree 、 Middle preface ; Preorder of right subtree 、 Middle preface , Processing recursively
// The original method is to copy a new array from the original array for each recursive processing , There are a lot of copies that take time
// Based on this situation , You can use subscript movement , Instead of copying from the original array , Optimize
// You need to know the subscript at the beginning of this round of recursive preorder 、 Ending subscript ; Subscript at the beginning of middle order 、 Ending subscript ;
public TreeNode buildTreeOptimize(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0) {
return null;
}
// Each time, you need to find the location of the root node from the middle order sequence , You need to loop through an article , Consider using space for time , Use map Store the value corresponding to the subscript in advance
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
}
private TreeNode buildTree(int[] preorder, int[] inorder, int preorderStart, int preorderEnd,
int inorderStart, int inorderEnd) {
// Recursion end condition
if (preorderStart > preorderEnd) {
return null;
}
// The first element of the preorder is the root node
int rootValue = preorder[preorderStart];
// The position of the root node in the middle order
// int rootLocation = getIndexFromArray(rootValue, inorder, inorderStart, inorderEnd);
Integer rootLocation = map.get(rootValue);
// Number of left subtree nodes 、 Length of the preorder array
int leftLength = rootLocation - inorderStart;
// Find the left and right subtrees and start with the middle order 、 Ending subscript
TreeNode left = buildTree(preorder, inorder, preorderStart + 1, preorderStart + leftLength,
inorderStart, rootLocation - 1);
TreeNode right = buildTree(preorder, inorder, preorderStart + leftLength + 1, preorderEnd,
rootLocation + 1, inorderEnd);
return new TreeNode(rootValue, left, right);
}
LeetCode Time consuming :1ms
- summary
- Be familiar with the characteristics of pre order, middle order and post order , Find out the rules of constructing trees
- Familiar with the application of tree recursion
- Involving from the original array copy A new array for recursive processing , You can use the subscript of an array instead of , Start subscript 、 The end subscript indicates the range of an array
边栏推荐
- 【错误记录】Android 应用安全检测漏洞修复 ( StrandHogg 漏洞 | 设置 Activity 组件 android:taskAffinity=““ )
- Daily problem essay | 21.11.29: use resttemplate to call external put request, and prompt '400 bad request'
- Middleware_ Redis_ 05_ Persistence of redis
- [mavros] mavros startup Guide
- How to download web photos
- [ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design
- There is a problem with numpy after CONDA installs pytoch
- 1.6 Px4 initialization calibration
- 關於概率統計中的排列組合
- ros缺包怎么办
猜你喜欢

1.5、PX4载具选择

關於概率統計中的排列組合
![[leetcode] intersecting linked list](/img/e0/ee1b0503f92b42916d81fda02129ba.jpg)
[leetcode] intersecting linked list
![[Li mu] how to read papers [intensive reading of papers]](/img/41/7e1ff1db2f7a848c8702c186c79fe5.jpg)
[Li mu] how to read papers [intensive reading of papers]

1.3 ROS 无人机简介

On permutation and Combination in Probabilistic Statistics

Leetcode binary tree problem

Record the packaging of the googlechrome browser plug-in

从解读 BDC 自动生成的代码谈起,讲解 SAPGUI 的程序组成部分试读版

2021-02-27image processing of MATLAB
随机推荐
Leetcode 1248 count number of nice subarrays
The problem of slow response of cs-3120 actuator during use
Leetcode 430 flat a multilevel double linked list (DFS linked list)
Tencent Cloud Database tdsql - Dajia comments | The Past, Present and Future of basic software
[ROS] review of 2021 ROS Summer School
Matlab array other common operation notes
Leetcode 698 partition to K equal sum subsets (DFS pruning)
2021-3-1MATLAB写cnn的mnist数据库训练
Derivation of Kalman filter (KF) and extended Kalman filter (EKF)
负数+0+正数
What if ROS lacks a package
On permutation and Combination in Probabilistic Statistics
PX4装机教程(六)垂起固定翼(倾转)
Using completabilefuture
Kubernetes binary installation (v1.20.15) (VII) plug a work node
Daily problem essay | 21.11.29: use resttemplate to call external put request, and prompt '400 bad request'
Xpath注入
“看似抢票实际抢钱”,别被花式抢票产品一再忽悠
【ROS】ROSmsg cakin_ Make compilation error
Multi interest recall model practice | acquisition technology