当前位置:网站首页>Detailed explanation of leetcode reconstruction binary tree [easy to understand]
Detailed explanation of leetcode reconstruction binary tree [easy to understand]
2022-07-01 13:31:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
LeetCode Detailed explanation of reconstructing binary tree
Title Description
Principle analysis
(1) General train of thought
So let's talk about that , The former sequence traversal + How to determine a unique binary tree by middle order traversal . Basic knowledge about binary tree , Please have a look at Basic operation and connection of binary tree . This will not be repeated too much . For the preorder traversal order : root 、 The left subtree 、 Right subtree ; For the traversal order of the middle order : The left subtree 、 root 、 Right subtree . So through preorder traversal , The first node we get in the preamble is the root of the tree , Then find the position of the node in the middle order traversal . In the middle order , All the nodes on the left side of the root belong to the left subtree of the root , The right side of the root is full of nodes belonging to the right subtree of the root . Details are shown in the picture :
After the first step , We will find that , At present, we only specifically determine which is the root node , Which nodes belong to the left and right subtrees . But because of the tree Recursive property . The nodes belonging to the left subtree still conform to the preorder traversal , The characteristics of medium order traversal . So we just need to use the above method again for the two parts just separated , Determine the root node , Determine which nodes belong to the left subtree , Which nodes belong to the right subtree . One analogy , Until the end . This is the general idea of this problem .
(2) Detailed description
There are still many places worth thinking about this problem . 1、 How can we express which nodes belong to the left subtree , Right subtree ? answer : Before the order 、 The middle order is given vector, So we can determine the range by subscript . Before the order :【 root , The left subtree , Right subtree 】. Middle preface :【 The left subtree , root , Right subtree 】. They are all three categories, and the nodes are all concentrated , Good distinction . 2、 What is the end condition of recursion ? answer : This still needs to be combined with specific code analysis , What is certain at present is , When we control the scope , If the scope is illegal ( non-existent ) The situation shows that there is no left subtree or right subtree , We're going back to .
Code implementation
notes : Usually in my solution , Range control , The reason why the code is written in this way will be written next to the corresponding code through comments , Help readers understand the analysis code , This is more targeted . therefore , If the reader has doubts or does not understand the previous topic analysis , Please read the code and the notes carefully , It will inspire you , Help you understand !!
(1) The main function
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
//_buildTree This problem requires recursive implementation , So we need to use a recursive function .
return _buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}Here I want to explain in detail the parameters and functions of this recursive function The first parameter : It's the preorder traversal vector, There's not much to explain The second parameter :preStart, It is at the beginning of the preorder of the subproblem . Say in detail , After we determine the root , We will recurse the left and right subtrees , The starting position of the left and right subtrees should be determined . The third parameter :preEnd: It is at the end of the preorder of the subproblem , This guarantees preStart And preEnd Between them is the node sequence of the subproblem . Fourth parameter It is traversal in middle order vector Fifth parameter :inStart, Is the starting position of the order traversal in the subproblem Sixth parameter :inEnd, Is the end position of the sequence traversal in the sub problem
(2) Recursive function
TreeNode* _buildTree(vector<int>& preorder,int preStart,int preEnd,vector<int>&inorder,int inStart,int inEnd)
{
if(preStart>preEnd)
{
return nullptr;
}
// We can directly determine the root node , So we first create the root node
TreeNode* root = new TreeNode(preorder[preStart]);
// After finding the root node , We take the value of the root node and find the corresponding position in the middle order traversal , Distinguish left and right subtrees
for(int i=inStart;i<=inEnd;i++)
{
// Find the middle order traversal position of the root node
if(inorder[i] == preorder[preStart])
{
// Because the recursive function completes the construction of the sub problem tree , All that make a big problem root The left and right subtrees can be linked separately
root->left = _buildTree(preorder,preStart+1,preStart+i-inStart,inorder,inStart,i-1);
root->right = _buildTree(preorder,preStart+i-inStart+1,preEnd,inorder,i+1,inEnd);
}
}
return root;
}Determination of parameter interval
The key is how many parameters are passed in the recursive subproblem .
size:size Is the number of nodes in the left subtree, so size = i-inStart therefore :root->left = _buildTree(preorder,preStart+1,preStart+i-inStart,inorder,inStart,i-1); xxxxxxroot->right = _buildTree(preorder,preStart+i-inStart+1,preEnd,inorder,i+1,inEnd); Readers can understand by comparing themselves
The condition for the end of recursion
The next step is to determine how to end recursion , Is the first recursive function if. We mentioned that before , If the interval of the subtree of the subproblem does not exist, the cycle can be ended , So how can it be called nonexistence ? We have just obtained the range of the preorder of each subtree 【preStart,preEnd】, If preStart==preEnd When , It means that the subtree also has a node , Still need to cycle , But is it possible preStart>preEnd Well ? The answer is yes . When we find the recursive subproblem preStart = preStart+1,preStart Growing , And recursive subproblem preEnd = preStart+size-1. The analysis and comparison are : When the subtree has only one node (size == 1) yes ,preStart == preEnd. After recursion again ,size == 0, therefore preStart > preEnd. It means there is no subtree , Can return nullptr 了 . So get the code :if (preStart>preEnd) return nullptr;
summary
xxxx See the binary tree problem , What our prime minister should think of is function recursion , Therefore, binary tree has good “ Recursive property ”, Every subtree is a binary tree , All meet the characteristics of trees , If the subproblem has the same characteristics, recursive algorithm can be used . Secondly, we should know clearly , Binary tree “ front 、 in 、 after , Sequence traversal ”, And know the relationship and differences between them . After having the above thoughts and reserve knowledge , We can write code logic with certain ideas . Another important part of this problem is the preface of the control subproblem 、 Middle preface vector Scope limit of . Truly ensure the unity of the subproblem and the original problem xxxx This is the complete analysis of this problem , If you have a better idea , Or where I can optimize my code , Please point out , I will study with an open mind . I hope we can study together , Progress together !!
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/131500.html Link to the original text :https://javaforall.cn
边栏推荐
- Analysis report on the development prospect and investment strategy of the global and Chinese laser chip industry Ⓑ 2022 ~ 2027
- Flutter SQLite使用
- MySQL statistical bill information (Part 2): data import and query
- A Fletter version of Notepad
- SAP 智能机器人流程自动化(iRPA)解决方案分享
- Jenkins+webhooks- multi branch parametric construction-
- Listen in the network
- Example code of second kill based on MySQL optimistic lock
- Leetcode第一题:两数之和(3种语言)
- 1.8 new features list
猜你喜欢

minimum spanning tree

Feign & Eureka & zuul & hystrix process

spark源码(五)DAGScheduler TaskScheduler如何配合提交任务,application、job、stage、taskset、task对应关系是什么?

5. Use of ly tab plug-in of header component

【大型电商项目开发】性能压测-压力测试基本概念&JMeter-38

Different test techniques

刘对(火线安全)-多云环境的风险发现

Jenkins+webhooks- multi branch parametric construction-

9. Use of better scroll and ref

焱融看 | 混合云时代下,如何制定多云策略
随机推荐
Idea of [developing killer]
During Oracle CDC data transmission, the CLOB type field will lose its value during update. There is a value before update, but
Function test process in software testing
Analysis report on production and marketing demand and investment forecast of global and Chinese diamond powder industry Ⓤ 2022 ~ 2027
8 popular recommended style layout
游戏公会在去中心化游戏中的未来
Yarn restart applications record recovery
Have you ever encountered the problem that flynk monitors the PostgreSQL database and checkpoints cannot be used
【牛客刷题-SQL大厂面试真题】NO2.用户增长场景(某度信息流)
Use of shutter SQLite
Application of 5g industrial gateway in scientific and technological overload control; off-site joint law enforcement for over limit, overweight and overspeed
焱融看 | 混合云时代下,如何制定多云策略
MySQL报错1040Too many connections的原因以及解决方案
Detailed explanation of OSPF LSA of routing Foundation
Report on the "14th five year plan" and scale prospect prediction of China's laser processing equipment manufacturing industry Ⓢ 2022 ~ 2028
科学创业三问:关于时机、痛点与重要决策
Google Earth engine (GEE) - Global Human Settlements grid data 1975-1990-2000-2014 (p2016)
Yarn重启applications记录恢复
Analysis report on the development trend and prospect scale of silicon intermediary industry in the world and China Ⓩ 2022 ~ 2027
How much money do novices prepare to play futures? Is agricultural products OK?