当前位置:网站首页>Sword finger offer 23 - print binary tree from top to bottom
Sword finger offer 23 - print binary tree from top to bottom
2022-07-06 14:18:00 【Snail Internet】
Binary tree structure
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
Title Description
- Print each node of the binary tree from top to bottom , The nodes of the same layer are printed from left to right .
analysis
- Investigate sequence traversal
- Every time I print a node , If the node has child nodes , Then put the child nodes of this node at the end of a queue .
- Next, the head of the queue takes out the node that first entered the queue , Repeat the previous print operation , Until all nodes in the queue are printed .
Code implementation
public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root==null){
return list;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode treeNode = queue.poll();
if (treeNode.left != null) {
queue.offer(treeNode.left);
}
if (treeNode.right != null) {
queue.offer(treeNode.right);
}
list.add(treeNode.val);
}
return list;
}
Auxiliary package
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
边栏推荐
- 强化学习基础记录
- Experiment 7 use of common classes (correction post)
- 7-11 机工士姆斯塔迪奥(PTA程序设计)
- 实验七 常用类的使用(修正帖)
- 7-14 error ticket (PTA program design)
- Record an edu, SQL injection practice
- Callback function ----------- callback
- XSS之冷门事件
- Record once, modify password logic vulnerability actual combat
- 7-6 local minimum of matrix (PTA program design)
猜你喜欢
攻防世界MISC练习区(gif 掀桌子 ext3 )
强化学习基础记录
Programme de jeu de cartes - confrontation homme - machine
Windows platform mongodb database installation
Build domain environment (win)
On the idea of vulnerability discovery
网络基础之路由详解
Hackmyvm target series (4) -vulny
How to turn wechat applet into uniapp
Strengthen basic learning records
随机推荐
Web vulnerability - File Inclusion Vulnerability of file operation
Brief introduction to XHR - basic use of XHR
7-7 7003 组合锁(PTA程序设计)
List and data frame of R language experiment III
SRC mining ideas and methods
实验五 类和对象
Data mining - a discussion on sample imbalance in classification problems
Sqqyw (indifferent dot icon system) vulnerability recurrence and 74cms vulnerability recurrence
[data processing of numpy and pytoch]
[experiment index of educator database]
攻防世界MISC练习区(SimpleRAR、base64stego、功夫再高也怕菜刀)
Hackmyvm target series (2) -warrior
[insert, modify and delete data in the headsong educator data table]
7-8 7104 约瑟夫问题(PTA程序设计)
xray与burp联动 挖掘
Attack and defense world misc practice area (simplerar, base64stego, no matter how high your Kung Fu is, you are afraid of kitchen knives)
7-4 散列表查找(PTA程序设计)
小程序web抓包-fiddler
攻防世界MISC练习区(gif 掀桌子 ext3 )
Hackmyvm target series (3) -visions