当前位置:网站首页>Some recursive and iterative problem solving ideas of binary tree (clear and easy to understand)
Some recursive and iterative problem solving ideas of binary tree (clear and easy to understand)
2022-06-25 18:26:00 【Zebra and running】
Catalog
(1). Traversal in front, middle and back order
(2). Classical recursive solution
(1) For example, judge whether a tree is a balanced binary tree
(2) Merge two binary trees into a binary tree
Two . iteration ( Sequence traversal )
(1). Normal sequence traversal
(2). Layered sequence traversal
(3). With depth (depth) And serial number (pos) Sequence traversal of
One . recursive
(1). Traversal in front, middle and back order
The essence is the same , The main reason is that the current traversal node is processed in different ways .
The method of traversal before, during and after the sequence can refer to my other blog
https://blog.csdn.net/qq_24016309/article/details/122382593
(2). Classical recursive solution
(1) For example, judge whether a tree is a balanced binary tree
Given a binary tree , Determine whether the binary tree is a balanced binary tree . For standard LeetCode The first 110 topic
Ideas : Whether a tree is a balanced binary tree ,
- First, judge whether the left subtree of the tree is a balanced binary tree
- Then judge whether the right subtree of the tree is a balanced binary tree
- Judge whether the current height difference between the left and right subtrees > 1
If you write recursion directly, there will be many repeated operations when calculating the height of the tree .
ps: Optimal solution : Start with the function of tree height , If the left and right subtrees have one -1 Just go back to -1, Height difference >1 Also returned -1. Then we can find the height of the tree directly , If the tree height is not -1, That's the balanced binary tree . This method finds the function with repeated operation , And the targeted optimization of this function is worth noting .
(2) Merge two binary trees into a binary tree
The rule for merging is if two nodes overlap , Then add their values as the new values after node merging , Otherwise, no NULL The node of will be the node of the new binary tree directly . For standard LeetCode The first 617 topic
Ideas : To merge two binary trees ,
- First, if one of the two incoming trees is empty , Then just go back to another tree
- If neither tree is empty , It would be new A new root node , The value is equal to the sum of the values of the root nodes of the two trees
- then node.left=merge( Of the first tree left, Of the second tree left);node.right = merge( Of the first tree right, Of the second tree right)
Two . iteration ( Sequence traversal )
(1). Normal sequence traversal
Using the queue , Sequence traversal
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
TreeNode node = queue.remove();
System.out.println(node);
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}(2). Layered sequence traversal
If we want to traverse the sequence layer by layer , Then you can use the queue size function , Before the start of each cycle , Get the length of the current queue first , That is, the number of nodes in the current layer , Then go to another while loop , loop size Just turn . For standard LeetCode The first 102 topic ( It is required to put the elements of each layer into different list Collection ).
while (!queue.isEmpty()){
int size = queue.size();
List<Integer> listEle = new ArrayList<>();
while (size > 0){
TreeNode node = queue.remove();
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
listEle.add(node.val);
size--;
}
list.add(listEle);
}(3). With depth (depth) And serial number (pos) Sequence traversal of
Define one for yourself MyNode, It stores a depth (depth) And serial number (pos), It is used to represent the serial number of the current node , Note that the sequence number of the root node is 0 still 1, This is for the children pos It's influential .
Such as LeetCode The first 662 topic , I want you to find the width of the binary tree , Mainly, there may be a large area without nodes in the middle , It is not easy to traverse with normal sequence .
Ideas : Sequence traversal + Using the properties of the queue's head and tail
Before each cycle , Get the first and last elements in the current queue , According to their pos The difference between the , Maintenance ans, That is, the maximum width .
class MyNode{
TreeNode node;
int depth;
int pos;
public MyNode(TreeNode node, int depth, int pos) {
this.node = node;
this.depth = depth;
this.pos = pos;
}
}class Solution {
public int widthOfBinaryTree(TreeNode root) {
Deque<MyNode> queue = new LinkedList<>();
int ans = 0;
queue.add(new MyNode(root,0,0));
while (!queue.isEmpty()){
int size = queue.size();
ans = Math.max(queue.getLast().pos-queue.getFirst().pos+1,ans);
while (size > 0){
MyNode myNode = queue.remove();
if (myNode.node.left != null){
queue.add(new MyNode(myNode.node.left,myNode.depth+1,myNode.pos*2+1));
}
if (myNode.node.right != null){
queue.add(new MyNode(myNode.node.right,myNode.depth+1,myNode.pos*2+2));
}
size--;
}
}
return ans;
}
}边栏推荐
- 【深入理解TcaplusDB技术】TcaplusDB导入数据
- 【深入理解TcaplusDB技术】TcaplusDB新增机型
- Slam visuel Leçon 14 leçon 9 filtre Kalman
- Solve nvprof error err_ NVGPUCTRPERM - The user does not have permission to profile on the target device.
- new TypeReference用法 fastjson[通俗易懂]
- Move graph explorer to jupyterab: use ges4jupyter to connect ges and explore graphs
- What is an operator?
- Chapter 4:win10 installing mingw64
- 揭秘GES超大规模图计算引擎HyG:图切分
- ASP. Net supermarket convenience store online shopping mall source code, for the surrounding distribution system
猜你喜欢

【深入理解TcaplusDB技术】Tmonitor系统升级

【深入理解TcaplusDB技术】单据受理之创建业务指南
![There is a repeating element iii[pruning with ordered ordering]](/img/26/5c3632a64945ea3409f8240ef5b18a.png)
There is a repeating element iii[pruning with ordered ordering]

Matlab中图形对象属性gca使用
![[deeply understand tcapulusdb technology] transaction execution of document acceptance](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[deeply understand tcapulusdb technology] transaction execution of document acceptance

.NET Worker Service 如何优雅退出

One article solves all search backtracking problems of Jianzhi offer
![[deeply understand tcapulusdb technology] create a game area for document acceptance](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[deeply understand tcapulusdb technology] create a game area for document acceptance
![[in depth understanding of tcapulusdb technology] tcapulusdb construction data](/img/64/4d7ec393d8469cdadc89078a8cf4b1.png)
[in depth understanding of tcapulusdb technology] tcapulusdb construction data

Leetcode force buckle (Sword finger offer 26-30) 26 Substructure of tree 27 Image of binary tree 28 Symmetric binary tree 29 Print matrix 30 clockwise Stack containing min function
随机推荐
Solve nvprof error err_ NVGPUCTRPERM - The user does not have permission to profile on the target device.
C#泛型类案例
Using QT to make a beautiful login interface box
【深入理解TcaplusDB技术】TcaplusDB导入数据
Part 5:vs2017 build qt5.9.9 development environment
[in depth understanding of tcapulusdb technology] tcapulusdb regular documents
Redis trend - NVM memory
安装spark + 用命令运行scala相关项目 + crontab定时执行
【深入理解TcaplusDB技术】集群管理操作
.NET Worker Service 添加 Serilog 日志记录
Dell r530 built in hot spare status change description
【flutter 页面跳转后退如何刷新?】
Uncover ges super large scale graph computing engine hyg: Graph Segmentation
Android Internet of things application development (smart Park) - picture preview interface
揭秘GES超大规模图计算引擎HyG:图切分
Is it safe for a securities company to open an account with the lowest handling fee among the top ten
[in depth understanding of tcapulusdb technology] form creation and approval of document acceptance
[path planning] how to add moving objects to a path
IVX sailing
存在重复元素III[利用排序后的有序性进行剪枝]