当前位置:网站首页>Jianzhi offer 07 rebuild binary tree -- construct binary tree from middle order and post order traversal sequence
Jianzhi offer 07 rebuild binary tree -- construct binary tree from middle order and post order traversal sequence
2022-07-27 13:42:00 【Yang, who wants to get up early】
The finger of the sword Offer 07. Reconstruction of binary tree
The finger of the sword Offer 07. Reconstruction of binary tree
Enter the results of preorder traversal and inorder traversal of a binary tree , Build the binary tree and return its root node .
It is assumed that the results of the input preorder traversal and the middle order traversal do not contain repeated numbers .
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]
Thought analysis
First of all, you need to know what characteristics the traversed array has
- In the preorder traversal sequence , The first element is the root node of the tree
- In the middle order traversal sequence , The left side of the root node is the left subtree , The right side of the root node is the right subtree
According to the above theoretical knowledge, we can know the problem-solving strategy of this problem , That is to say The first element of the preamble array 【 The root node 】 Is the cutting point , Cut the array in the middle first , According to the middle order array , In turn, order the array before cutting . Cut one layer at a time , The first element of each pre ordered array is the node element .

The first element of the preorder traversal is its head node . Got the head node , We can find the position of the head node in the middle order traversal index. adopt index We can find the length of the left subtree in the array : index - inorder_start.(inorder_start It is the starting point of middle order traversal ).
Get the head node of the tree
int root_val = preorder[preorder_start](preorder_start Is the starting value of preorder traversal ). Then we build the binary tree directly The root nodeTreeNode* root = new TreeNode(root_val)Build the left tree :
root->leftWe know that the length of the left subtree of the binary tree isleft_length = index - inorder_startSo we can deduce that the position of the left subtree of the binary tree in the preorder traversal is
[preorder_start+1,preorder_start+left_length].
Empathy : The position of the left subtree of the binary tree in the middle order traversal is[inorder_start, index - 1].Build the right tree :
root->right
The position of the right subtree of the binary tree in the preorder traversal is[preorder_start+left_length+1,preorder_end].
Empathy : The position of the right subtree of the binary tree in the middle order traversal is[index + 1 , inorder_end].
The code is as follows :
class Solution {
public:
// Recursive code
TreeNode* buildcore(const vector<int>& preorder, const vector<int>& inorder, int preorder_start, int preorder_end, int inorder_start, int inorder_end)
{
if(preorder_start>preorder_end||inorder_start>inorder_end)
{
return nullptr;
}
// The first number of preorder traversal is the value of the root node
int root_val = preorder[preorder_start];
TreeNode* root = new TreeNode(root_val);
// There is only one value in the interval , return
if(preorder_start == preorder_end)
{
return root;
}
// Middle order traversal finds the location of the root node
int index = 0;
// Can be equal to , In scope
while(index <= inorder_end && inorder[index] != root_val)
{
index++;
}
// If index Greater than inorder_end, It means that we didn't find , Report errors , The meaning of the title is that you can definitely find , So there is no judgment here .
// The interval size of left and right subtrees .
int left_length = index - inorder_start;
root->left = buildcore(preorder,inorder,preorder_start+1,preorder_start+left_length,inorder_start,index-1);
root->right = buildcore(preorder,inorder,preorder_start+left_length+1,preorder_end,index+1,inorder_end);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
int n = preorder.size();
if(n==0)
{
return 0;
}
return buildcore(preorder,inorder,0,n-1,0,n-1);
}
};
106. Construct binary tree from middle order and post order traversal sequence
106. Construct binary tree from middle order and post order traversal sequence
This question is similar to the previous one , The same solution can be used to solve recursively .
Thought analysis
In a postorder traversal sequence , The last element is the root node of the tree
In the middle order traversal sequence , The left side of the root node is the left subtree , The right side of the root node is the right subtree
With The last element of the sequenced array 【 The root node 】 Is the cutting point , Cut the array in the middle first , According to the middle order array , Conversely, after cutting the array . Cut one layer at a time , The last element of each subsequent array is the node element .
class Solution {
public:
TreeNode* buildcore(const vector<int>& inorder, const vector<int>& postorder, int inorder_start, int inorder_end, int post_start, int post_end)
{
if(inorder_start>inorder_end||post_start>post_end)
{
return nullptr;
}
// The last value of post order traversal is the root node
int root_val = postorder[post_end];
TreeNode* root = new TreeNode(root_val);
// Traverse to find the position of the root node in the middle order
int index = 0;
for(index = 0; index<= inorder_end; index++)
{
if(inorder[index] == root_val)
{
break;
}
}
// Calculate the length of the left subtree
int left_length = index - inorder_start;
// Build the left subtree
root->left = buildcore(inorder,postorder,inorder_start,index-1,post_start,post_start+left_length-1);
// Build the right subtree
root->right = buildcore(inorder,postorder,index+1,inorder_end,post_start+left_length,post_end-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
int n = inorder.size();
if(n==0)
{
return nullptr;
}
return buildcore(inorder,postorder,0,n-1,0,n-1);
}
};
边栏推荐
- Redis summary: cache avalanche, cache breakdown, cache penetration and cache preheating, cache degradation
- Musk was exposed to be the founder of Google: he broke up his best friend's second marriage and knelt down to beg for forgiveness
- Come and watch, 17 practical skills of operation and maintenance~
- 7.26 simulation summary
- echart折线图默认显示最后一个点以及纵向虚线
- Using ebpf to detect rootkit vulnerabilities
- C ftp add, delete, modify, query, create multi-level directory, automatic reconnection, switch directory
- MySQL高可用实战方案——MHA
- Feign's dynamic proxy
- Write a program, accept a string consisting of letters, numbers and spaces, and a character, and then output the number of characters in the input string. Case insensitive.
猜你喜欢

Classification and application of slip rings

使用碳刷的注意事项有哪些

Preliminary discussion on NetGen and Gmsh mesh generation of any multiple sub models of CAD based on osg+occ

电气成套企业如何借助ERP系统,做好成本利润管理?
![51: Chapter 5: develop admin management services: 4: develop [add admin account, interface]; (only [user name + password, method]; [@t...] annotation controls transactions; when setting cookies, do yo](/img/6f/4f93eca1d923a58b2ef4b1947538be.png)
51: Chapter 5: develop admin management services: 4: develop [add admin account, interface]; (only [user name + password, method]; [@t...] annotation controls transactions; when setting cookies, do yo

QT excellent open source project 13: qscintilla

Additional: [urlencoder.encode (string to be encoded, "encoding method");] (what is it?; why do we use this to encode when we set values in cookies?) (to be improved...)

Go语言系列:如何搭建Go语言开发环境?

for .. of可用于哪些数据的遍历

常见分布式理论(CAP、BASE)和一致性协议(Gosssip、Raft)
随机推荐
Keras深度学习实战——推荐系统数据编码
Qt剪切板QClipboard 复制粘贴自定义数据
OPPO 自研大规模知识图谱及其在数智工程中的应用
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(九)
Conditions and procedures of futures account opening
Set up SSH key based authentication using putty
W3school navigation bar exercise
js回调函数(callback)
2、Citrix Virtual Apps and Desktops 2203剪贴板重定向策略
Design of network abnormal traffic analysis system
滑环设备怎么进行维护
51:第五章:开发admin管理服务:4:开发【新增admin账号,接口】;(只开发了【用户名+密码的,方式】;【@T…】注解控制事务;设置cookie时,是否需要使用URLEncoder去编码;)
Gray histogram
Tencent cloud and the China Federation of industry released the research results of industrial AI quality inspection standardization to accelerate the intelligent transformation of manufacturing indus
Classification and application of slip rings
MFC FTP创建多级文件夹、上传文件到FTP指定目录
Evconnlistener of libevent_ new_ bind
Image features and extraction
Application of responsibility chain model in transfer accurate valuation
shell环境变量以及set,env,export的区别