当前位置:网站首页>【LeetCode】106. Construct binary tree from middle order and post order traversal sequence (wrong question 2)
【LeetCode】106. Construct binary tree from middle order and post order traversal sequence (wrong question 2)
2022-07-05 02:20:00 【Kaimar】
- Ideas
The result of middle order traversal is different from that of pre order traversal 、 Post order traversal for combination , Can uniquely identify a tree , Using traversal results to construct a tree is to do segmentation , Middle order and post order traversal combination , Determine the current node through the reverse order of post order traversal , Then divide the middle order to determine the left and right subtrees , Such as 3 Is divided into [9],[15, 20, 7] Respectively 3 Right and left subtrees .
Or recursion , So there is a recursive trilogy ( Write a version of the code and make mistakes , It was an error in cutting , It's better to recurse without knowing how to cut , Refer to the explanation of the question )
There are six steps in total :
First step : If the array size is zero , It indicates that the node is empty .
The second step : If it's not empty , Then take the last element of the subsequent array as the node element .
The third step : Find the position of the last element of the ordered array in the ordered array , As a cutting point
Step four : Cut the ordered array , Cut into middle order left array and middle order right array ( Don't reverse the order , It must be the first to cut the ordered array )
Step five : Cut sequential array , Cut into the left array and the right array
Step six : Recursively handle left and right intervals
The difficulty lies in how to cut , It is necessary to unify the opening and closing of the left and right , Then there is how to cut the sequence , How to find the cutting point of the subsequent array ?
There is no explicit cutting element in the subsequent array to cut left and right , Unlike a mid order array, there are clear cut points , Just separate the cutting points left and right .
At this point, there is a very heavy point , That is, the size of the middle order array must be the same as that of the later order array ( This is inevitable ).
- summary
This problem knows that thinking and writing code are two different things , There are still many difficulties in writing code , One is when to return , The second is how to split the middle order and post order arrays , The third is the segment details .
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func buildTree(inorder []int, postorder []int) *TreeNode {
// 1. Array is empty , Null node
nLen := len(inorder)
if nLen == 0 {
return nil
}
// 2. Not empty , Then the last node of post order traversal is taken as the root node
// A special case , Only one is leaf node , Go straight back to
root := &TreeNode{
Val : postorder[nLen - 1],
Left : nil,
Right : nil,
}
if nLen == 1 {
return root
}
// 3. Find the split point in the middle order traversal
var i int
for i = 0; i < nLen; i++ {
if inorder[i] == postorder[nLen - 1] {
break
}
}
// 4. Divide the middle order traversal array
// [0, i)
leftInorder := inorder[:i]
// [i + 1, len(inorder))
rightInorder := inorder[i + 1 :]
// 5. After splitting, traverse the array
// Lose the last
postorder = postorder[: len(postorder) - 1]
// Find the dividing point through the length
point := len(leftInorder)
// [0, point)
leftPostorder := postorder[: point]
// [point, len(postorder))
rightPostorder := postorder[point : ]
// 6. Recursion goes to the next level
root.Left = buildTree(leftInorder, leftPostorder)
root.Right = buildTree(rightInorder, rightPostorder)
return root
}
边栏推荐
- Win:使用 PowerShell 检查无线信号的强弱
- [uc/os-iii] chapter 1.2.3.4 understanding RTOS
- Yolov5 model training and detection
- RichView TRVUnits 图像显示单位
- Talk about the things that must be paid attention to when interviewing programmers
- Use the difference between "Chmod a + X" and "Chmod 755" [closed] - difference between using "Chmod a + X" and "Chmod 755" [closed]
- Win:使用 Shadow Mode 查看远程用户的桌面会话
- Unified blog writing environment
- Educational Codeforces Round 122 (Rated for Div. 2) ABC
- Binary tree traversal - middle order traversal (golang)
猜你喜欢
Matrixone 0.2.0 is released, and the fastest SQL computing engine is coming
Binary tree traversal - middle order traversal (golang)
Can you really learn 3DMAX modeling by self-study?
Application and Optimization Practice of redis in vivo push platform
Yolov5 model training and detection
Exploration of short text analysis in the field of medical and health (I)
[Digital IC hand tearing code] Verilog edge detection circuit (rising edge, falling edge, double edge) | topic | principle | design | simulation
Comment mettre en place une équipe technique pour détruire l'entreprise?
Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
Action News
随机推荐
如何搭建一支搞垮公司的技術團隊?
He was laid off.. 39 year old Ali P9, saved 150million
Five ways to query MySQL field comments!
How to find hot projects in 2022? Dena community project progress follow-up, there is always a dish for you (1)
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
Exploration of short text analysis in the field of medical and health (I)
I use these six code comparison tools
Introduce reflow & repaint, and how to optimize it?
Lsblk command - check the disk of the system. I don't often use this command, but it's still very easy to use. Onion duck, like, collect, pay attention, wait for your arrival!
Valentine's Day flirting with girls to force a small way, one can learn
[technology development-26]: data security of new information and communication networks
Kotlin - 协程 Coroutine
Variables in postman
JVM's responsibility - load and run bytecode
Flutter 2.10 update details
Learn game model 3D characters, come out to find a job?
Pytorch register_ Hook (operate on gradient grad)
官宣!第三届云原生编程挑战赛正式启动!
Timescaledb 2.5.2 release, time series database based on PostgreSQL
Security level