当前位置:网站首页>2022-003arts: recursive routine of binary tree
2022-003arts: recursive routine of binary tree
2022-07-02 04:39:00 【FlashSu】
ARTS:Algorithm、Review、Tip、Share
- Algorithm Algorithm problem
- Review English articles
- Tip Think back to a small skill learned at work this week
- Share Think about a technical point of view 、 Social hot spots 、 A product or a puzzle
Algorithm
Binary tree related topics , A large part can be solved by using the following recursive routine :
- Assume that any X A tree that is a head node , You can get any information from its left and right subtrees ;
- Under the assumptions of the previous step , Discuss with X A tree that is a head node , The possibility of getting the answer ;
- After listing all the possibilities , Determine what kind of information you need from the left tree and the right tree ;
- Find the complete set of left tree information and right tree information , Is the information that any subtree needs to return S;
- Recursive functions return S, Every sub tree asks so ;
- Write code , In the code, consider how to integrate the information of the left tree and the information of the right tree into the information of the whole tree .
Relevant video materials : Recursive routine of binary tree -time-57:45
958. The completeness test of binary tree
Given a binary tree root , Determine if it's a Perfect binary tree .
In a Perfect binary tree in , Except for the last level , All levels are completely filled , And all nodes in the last level are as far left as possible . It can contain 1 To 2h
The last level between nodes h .Example 1:
Input :root = [1,2,3,4,5,6] Output :true explain : Every floor before the last floor is full ( namely , The node value is {1} and {2,3}
The two layers ), And all nodes in the last layer ({4,5,6}) As far left as possible . Example 2:
Input :root = [1,2,3,4,5,null,7] Output :false explain : The value is 7 The node of is not as far to the left as possible .
Tips :
The number of nodes of the tree is in the range [1, 100] Inside . 1 <= Node.val <= 1000
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/check-completeness-of-a-binary-tree
Solution description
solution 1
First, let's talk about a solution that doesn't use the binary tree recursive routine , Judge whether a binary tree is a complete binary tree , The following two conditions can be passed :
- If a node has a right subtree , Then it must have a left subtree ;
- After encountering incomplete nodes , The nodes behind the hierarchy traversal must be leaf nodes .
As mentioned above , You can use hierarchical traversal , Check the left and right child nodes of each node at once , Whether to violate any of the above conditions , If there is a direct return false, Otherwise, traverse all nodes , Then the tree is a complete binary tree .
solution 2
According to the idea of binary tree recursive routine , Under the assumption of the first step , Discuss with X Whether the tree with the head is a full binary tree , The possibilities of the answer are listed below :
- Left 、 All right subtrees are full binary trees , with X A tree with a head is a full binary tree ;
- The left subtree is a non full binary tree 、 The right subtree is a full binary tree , And the height of the left subtree is higher than that of the right subtree 1;
- The left subtree is a full binary tree 、 The right subtree is a non full binary tree , And left 、 The right subtree is equal in height .
Sum up , We need to turn left 、 The complete set of information required by the right subtree is : Is it a complete binary tree 、 Whether it is a full binary tree 、 What is the height
Called recursively , Get the corresponding information on all subtrees , Then process the same information , See the following code implementation for details
coded
public boolean isCompleteTree(TreeNode root) {
if (root == null) {
return true;
}
// method 01
//Queue<TreeNode> queue = new LinkedList<>();
//queue.add(root);
//
//boolean isStartLeaf = false;
//TreeNode node;
//TreeNode l;
//TreeNode r;
//while (!queue.isEmpty()) {
// node = queue.poll();
// l = node.left;
// r = node.right;
// if (r != null && l == null) {
// return false;
// }
// if (isStartLeaf && (l != null || r != null)) {
// return false;
// }
// if (l != null) {
// queue.add(l);
// }
// if (r != null) {
// queue.add(r);
// }
// if (!isStartLeaf && (l == null || r == null)) {
// isStartLeaf = true;
// }
//}
//return true;
// method 02
return process(root).isCBT;
}
public static class Info {
public boolean isFull;
public boolean isCBT;
public int height;
public Info(boolean full, boolean cbt, int h) {
isFull = full;
isCBT = cbt;
height = h;
}
}
public static Info process(TreeNode xNode) {
if (xNode == null) {
return new Info(true, true, 0);
}
Info leftInfo = process(xNode.left);
Info rightInfo = process(xNode.right);
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height;
boolean isCBT = false;
if (isFull) {
isCBT = true;
} else if (leftInfo.isCBT && rightInfo.isCBT) {
if (!leftInfo.isFull && rightInfo.isFull && leftInfo.height - rightInfo.height == 1) {
isCBT = true;
} else if (
leftInfo.isFull && rightInfo.isFull && leftInfo.height - rightInfo.height == 1
) {
isCBT = true;
} else if (
leftInfo.isFull && !rightInfo.isFull && leftInfo.height == rightInfo.height
) {
isCBT = true;
}
}
return new Info(isFull, isCBT, height);
}
Review
NewCollectionTypesExplained Some common business scenarios , Use JDK The implementation of the collection framework is cumbersome ,Guava In response to this problem , Yes JDK The collection framework type of , This article wiki It is introduced in detail :
- Multiset It is used to count elements that may appear multiple times , It can be downloaded from unordered ArrayList、Map<E, Integer> Two API Understand from the perspective
Tip
The first working week after the year , Most of my colleagues were on compensatory leave two days ago , While completing relevant work this week , It is also mainly to be familiar with the previous business 、 Code , Encountered no document 、 Or there are documents and the description is simple , There is code but no comments 、 The code logic is disordered .
Apart from a few complaints , I can only ask myself more 、 Get familiar with 、 Start documenting .
Share
When you encounter business scenarios you need to be familiar with at work 、 Complex code flow , Effective means can be achieved by communicating with relevant colleagues , The more direct way is to actually go through the process by yourself ,debug Go through the relevant code , Although it may be troublesome , But it can go deep into the details , clarify 、 Sort out the possible questions at each node .
Not afraid of trouble 、 Be diligent in your hands .
边栏推荐
- Spring moves are coming. Watch the gods fight
- LeetCode-对链表进行插入排序
- Unity particle Foundation
- cookie、session、tooken
- Deep understanding of lambda expressions
- CY7C68013A之keil编译代码
- BGP experiment the next day
- Record the bug of unity 2020.3.31f1 once
- Message mechanism -- message processing
- Learn what definitelytyped is through the typescript development environment of SAP ui5
猜你喜欢

Common sense of cloud server security settings

Mapping location after kotlin confusion

10 minutes to understand CMS garbage collector in JVM

Let正版短信测压开源源码

Summary of common string processing functions in C language

Deeply understand the concepts of synchronization and asynchrony, blocking and non blocking, parallel and serial

unable to execute xxx. SH: operation not permitted

Read "the way to clean code" - function names should express their behavior

VMware installation win10 reports an error: operating system not found

Cache consistency solution - how to ensure the consistency between the cache and the data in the database when changing data
随机推荐
One click generation and conversion of markdown directory to word format
Markdown编辑语法
oracle 存储过程与job任务设置
Websites that it people often visit
cs架构下抓包的几种方法
How much can a job hopping increase? Today, I saw the ceiling of job hopping.
cookie、session、tooken
Arbre binaire pour résoudre le problème (2)
Pytoch --- use pytoch to predict birds
Pytorch---使用Pytorch实现U-Net进行语义分割
Exposure X8标准版图片后期滤镜PS、LR等软件的插件
powershell_ View PowerShell function source code (environment variable / alias) / take function as parameter
C language practice - binary search (half search)
缓存一致性解决方案——改数据时如何保证缓存和数据库中数据的一致性
Read "the way to clean code" - function names should express their behavior
Embedded-c language-9-makefile/ structure / Consortium
Pytorch---使用Pytorch进行图像定位
[JS -- map string]
Wechat applet pull-down loading more waterfall flow loading
Pytorch-Yolov5從0運行Bug解决:

