当前位置:网站首页>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 }
边栏推荐
- 市场监管总局、国家网信办:开展数据安全管理认证工作
- 语义向量检索入门教程
- Flowable workflow
- Streaming data warehouse storage: requirements and architecture
- Lambda intermediate operation limit
- Building circuits on glass
- Research Report on development status and investment suggestions of o-tert-butyl cyclohexyl acetate Market in the world and China 2022-2028
- [n32g457] remote monitoring of graffiti cloud based on RT thread and n32g457
- DevOps落地实践点滴和踩坑记录-(1)
- How to guarantee industrial control safety: system reinforcement
猜你喜欢

be based on. NETCORE development blog project starblog - (11) access statistics

What is the digital twin of Yixin Huachen and what is its application value?

'virtue and art' in the field of recurrent+transformer video recovery

Kill, pkill, killall, next, what I brought to you in the last issue is how to end the process number and rush!

Esp8266wifi development board collects temperature and humidity data and uploads them to the Internet of things platform

【ROE】(2)ROE协议

网狐游戏服务器-房间配置向导-组件属性与基本配置赋值

我在某大厂做软件测试工程师的《一天完整工作流程》

Before applying data warehouse ODBC, you need to understand these problems first

Explain asynchronous tasks in detail: the task of function calculation triggers de duplication
随机推荐
2022-06-11: note that in this document, graph is not the meaning of adjacency matrix, but a bipartite graph. In the adjacency matrix with length N, there are n points. Matrix[i][j] represents the dist
C dynamically calls the static library generated by go
What is the digital twin of Yixin Huachen and what is its application value?
河南中创|从云到边,边缘计算如何赋能数据中心
接口自动化测试很难?带你从0到1入门接口自动化测试【0基础也能看懂系列】
New knowledge: monkey improved app crawler
Crawler small case 04 - use beautiful soup to batch obtain pictures
Before applying data warehouse ODBC, you need to understand these problems first
Tianjin Port coke wharf hand in hand map flapping software to visually unlock the smart coke port
Article 8: Design of multi-functional intelligent trunk following control system | undergraduate graduation project - [reply and Q & a record of design completion]
[n32g457] remote monitoring of graffiti cloud based on RT thread and n32g457
[answer] is ubiquitous language a pseudo innovation?
Nat. Comm. | supercomputing +ai: providing navigation for natural product biosynthesis route planning
大厂测试员年薪30万到月薪8K,吐槽工资太低,反被网友群嘲?
Win jar package setting boot auto start
Low code platform design exploration, how to better empower developers
About MySQL password modification failure
Data visualization big screen - big screen cloud minimalist user manual
QApplication a (argc, argv) and exec() in the main function of QT getting started
Module 8 - Design message queue MySQL table for storing message data