当前位置:网站首页>Elementary OJ problem of binary tree
Elementary OJ problem of binary tree
2022-06-12 01:13:00 【4nc414g0n】
Initial order of binary tree OJ topic
Flip binary tree
link : Flip binary tree
Problem description
Turn over a binary tree
4 / \ 2 7 / \ / \ 1 3 6 9 Input 4 / \ 7 2 / \ / \ 9 6 3 1 Output
analysis :
The left and right child nodes are exchanged from the bottom of the binary tree to the root node
The code is as follows :void _invertTree(struct TreeNode* root) { if(root) { struct TreeNode*tmp=root->left; root->left=root->right; root->right=tmp; _invertTree(root->left); _invertTree(root->right); } } struct TreeNode* invertTree(struct TreeNode* root){ if(root==NULL) return root; _invertTree(root); return root; }
Symmetric binary tree
link : Symmetric binary tree
Problem description
Given a binary tree , Check if it is mirror symmetric .
for example , Binary tree [1,2,2,3,4,4,3] It's symmetrical . 1 / \ 2 2 / \ / \ 3 4 4 3 But the next one [1,2,2,null,3,null,3] It's not mirror symmetric : 1 / \ 2 2 \ \ 3 3
Method 1 analysis :( recursive )
- When the left and right child nodes are empty, it returns true
- Because it has been judged that left and right Whether all are empty , So the next step is to use ‘||’ As long as there is something blank, it will be different
(left->val==right->val)&&_isSymmetric(left->left,right->right)&&_isSymmetric(leftright,right->left)
Three ( The first judgment value , The last two recursions ) Phase and judgmentBe careful :It's the left child of the left child and the right child of the right child ( Mirror image )
Method 2( iteration , Advanced )(I haven't learned at the beginning)
The code is as follows :bool _isSymmetric(struct TreeNode* left,struct TreeNode* right) { if(left==NULL&&right==NULL) return true; if(left==NULL||right==NULL) return false;// Because it has been judged that left and right Whether all are empty , So here we use || As long as there is something blank, it will be different return (left->val==right->val)&& _isSymmetric(left->left,right->right)&& _isSymmetric(left->>right,right->left); } bool isSymmetric(struct TreeNode* root){ if(root==NULL) return true; return _isSymmetric(root->left,root->right); }
Binary tree traversal ( Build a binary tree )
link : Binary tree traversal
expand :
OnlyWith empty nodesThat is, in the question ‘#’ Can be traversed by the first order to establish a binary tree ,
In addition, it must beFirst order plus middle orderorPost sequence plus middle sequenceTo create a unique binary tree
Problem description
Make a program , Read in a string of traversal strings entered by the user , Build a binary tree based on this string ( Store... As a pointer ).
For example, the following pre order traversal string :
ABC##DE#G##F### among “#” It's a space , The space character represents an empty tree .
After the binary tree was established , Then the binary tree is traversed in middle order , Output traversal results .
analysis :
- Reusing the pre sequence traversal code in the tree building function just changes the printed code to root Of val Assignment and array subscript ++(
Subscript addressing is not a value transfer)- If it is null, it returns null and subscript ++
The code is as follows :
// Middle order traversal printing void InOrder(struct TreeNode* root) { if(root==NULL) return; InOrder(root->left); printf("%c ",root->val); InOrder(root->right); } // Build up trees struct TreeNode* CreatTree(char *str,int *size) { if(str[*size]=='#') { (*size)++; return NULL; } struct TreeNode*root=(struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val=str[*size]; (*size)++; root->left=CreatTree(str, size); root->right=CreatTree(str, size); return root; }
Balanced binary trees
link : Balanced binary trees
Problem description
Given a binary tree , Determine if it's a highly balanced binary tree .
In this question , A height balanced binary tree is defined as : Every node of a binary tree The absolute value of the height difference between the left and right subtrees is not more than 1 .
analysis :
Be careful :This problem is different from most binary tree recursion , This question is judged from top to bottom- The auxiliary function is the depth function of binary tree
(abs(left-right)<=1)&&isBalanced(root->left)&&isBalanced(root->right);As long as there is an unbalanced binary tree, it must return falseThe code is as follows :
int _isBalanced_Depth(struct TreeNode*root) { if(root==NULL) return 0; int left=_isBalanced_Depth(root->left); int right=_isBalanced_Depth(root->right); return left>right?left+1:right+1; } // This method is to judge whether the subtree is a balanced tree from top to bottom bool isBalanced(struct TreeNode* root){ if(root==NULL) return true; int left=_isBalanced_Depth(root->left); int right=_isBalanced_Depth(root->right); return (abs(left-right)<=1)&&isBalanced(root->left)&&isBalanced(root->right); }
The subtree of another tree
link : The subtree of another tree
Problem description
Here are two binary trees root and subRoot . test root Whether and subRoot Subtrees with the same structure and node values . If there is , return true ; otherwise , return false .
Binary tree tree A subtree of includes tree A node of and all descendants of this node .tree It can also be seen as a subtree of its own .
analysis :
- The auxiliary function is to judge the same number
- isSubtree Functions and isSametree Function because it has been determined that left and right Whether all are empty , So the next step is to use ‘||’ As long as there is something blank, it will be different
- stay isSubtree Function ‘||’ On the left for true You don't have to look on the right , On the left for false To the right
The code is as follows :
bool isSameTree(struct TreeNode* p, struct TreeNode* q){ if(p==NULL&&q==NULL) return true; if(p==NULL||q==NULL) return false; if(p->val!=q->val) return false; return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); } bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){ if(root==NULL&&subRoot==NULL) return true; if(root==NULL||subRoot==NULL) return false; if(isSameTree(root, subRoot)) return true; return isSubtree(root->left,subRoot)||isSubtree(root->right,subRoot); // use or On the left for true Just > Don't look on the right , On the left for false To the right }
边栏推荐
- Comparison of OpenCV basic codes of ros2 foxy~galactic~humble
- Recurrent+Transformer 视频恢复领域的‘德艺双馨’
- [工具] spacing.js 测间距
- 河南中创|从云到边,边缘计算如何赋能数据中心
- 100 deep learning cases | day 41: speech recognition - pytorch implementation
- 验证码是自动化的天敌?看看阿里P7大神是怎么解决的
- 一看就懂的JMeter操作流程
- C dynamically calls the static library generated by go
- MS-HGAT: 基于记忆增强序列超图注意力网络的信息扩散预测
- Make good use of these 28 tools, and the development efficiency soars
猜你喜欢

Nat. Comm. | 超算+AI: 为天然产物生物合成路线规划提供导航

Go out with a stream

接口自动化测试很难?带你从0到1入门接口自动化测试【0基础也能看懂系列】

Codemirror 2 - highlight only (no editor) - codemirror 2 - highlight only (no editor)

Weibull Distribution韦布尔分布的深入详述(1)原理和公式

Explain asynchronous tasks in detail: the task of function calculation triggers de duplication

Verification code is the natural enemy of automation? Let's see how Ali P7 solved it

Vscode - the problem of saving a file and automatically formatting the single quotation mark 'into a double quotation mark'

MS-HGAT: 基于记忆增强序列超图注意力网络的信息扩散预测

验证码是自动化的天敌?看看阿里P7大神是怎么解决的
随机推荐
The 14th five year plan and investment feasibility study report of global and Chinese hydraulic ester base oil industry 2022 ~ 2028
About MySQL password modification failure
Flowable workflow
[roe] (2) roe agreement
Recurrent+Transformer 视频恢复领域的‘德艺双馨’
Virtual human appears on the stage of the Winter Olympic Games, connecting elements of the meta universe
C language pointer and array - learning 23
How much is the child's critical illness insurance coverage appropriate? Which product is better now
How to optimize plantuml flow diagram (sequence diagram)
MS-HGAT: 基于记忆增强序列超图注意力网络的信息扩散预测
Esp8266wifi development board collects temperature and humidity data and uploads them to the Internet of things platform
Lambda中间操作map
Forecast report on industry operation and development strategy of global and Chinese suspension control station industry 2022-2028
LabVIEW Arduino electronic weighing system (project Part-1)
[answer] what does UML use to represent hexagonal architecture
Henan Zhongchuang - from cloud to edge, how edge computing enables data centers
Streaming data warehouse storage: requirements and architecture
Lambda创建流
Scope and category of C language variables - learning 20
[answer] is ubiquitous language a pseudo innovation?