当前位置:网站首页>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;
边栏推荐
- Intranet information collection of Intranet penetration (I)
- 强化学习基础记录
- 网络层—简单的arp断网
- Network layer - simple ARP disconnection
- 【头歌educoder数据表中数据的插入、修改和删除】
- Web vulnerability - File Inclusion Vulnerability of file operation
- Analysis of penetration test learning and actual combat stage
- Hackmyvm target series (2) -warrior
- AQS details
- Wei Shen of Peking University revealed the current situation: his class is not very good, and there are only 5 or 6 middle-term students left after leaving class
猜你喜欢
随机推荐
强化學習基礎記錄
Strengthen basic learning records
sqqyw(淡然点图标系统)漏洞复现和74cms漏洞复现
List and data frame of R language experiment III
Strengthen basic learning records
内网渗透之内网信息收集(五)
HackMyvm靶机系列(7)-Tron
AQS details
Meituan dynamic thread pool practice ideas, open source
Record a penetration of the cat shed from outside to inside. Library operation extraction flag
2022华中杯数学建模思路
7-6 local minimum of matrix (PTA program design)
Detailed explanation of network foundation routing
Experiment five categories and objects
Package bedding of components
The United States has repeatedly revealed that the yield of interest rate hiked treasury bonds continued to rise
Data mining - a discussion on sample imbalance in classification problems
Hackmyvm target series (4) -vulny
【educoder数据库实验 索引】
Record an edu, SQL injection practice