当前位置:网站首页>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;
边栏推荐
- Canvas foundation 2 - arc - draw arc
- 中间件漏洞复现—apache
- HackMyvm靶机系列(6)-videoclub
- MSF generate payload Encyclopedia
- 7-7 7003 combination lock (PTA program design)
- Web vulnerability - File Inclusion Vulnerability of file operation
- 网络基础之路由详解
- Intel oneapi - opening a new era of heterogeneity
- Windows platform mongodb database installation
- [dark horse morning post] Shanghai Municipal Bureau of supervision responded that Zhong Xue had a high fever and did not melt; Michael admitted that two batches of pure milk were unqualified; Wechat i
猜你喜欢
随机推荐
Sqqyw (indifferent dot icon system) vulnerability recurrence and 74cms vulnerability recurrence
附加简化版示例数据库到SqlServer数据库实例中
Hackmyvm target series (4) -vulny
Record an edu, SQL injection practice
Experiment 4 array
安全面试之XSS(跨站脚本攻击)
Hackmyvm Target Series (3) - vues
【MySQL-表结构与完整性约束的修改(ALTER)】
7-4 hash table search (PTA program design)
链队实现(C语言)
Hackmyvm target series (3) -visions
[err] 1055 - expression 1 of order by clause is not in group by clause MySQL
Applet Web Capture -fiddler
力扣152题乘数最大子数组
Ucos-iii learning records (11) - task management
The most popular colloquial system explains the base of numbers
C language file operation
7-15 h0161. Find the greatest common divisor and the least common multiple (PTA program design)
SQL注入
List and data frame of R language experiment III