当前位置:网站首页>二叉树相关知识
二叉树相关知识
2022-07-25 23:58:00 【Coding~Man】
1:二叉树的层序遍历->通过队列while实现
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null){
return res;
}
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(root);
while(!que.isEmpty()){
List<Integer> level = new ArrayList<Integer>();
int cursize = que.size();
for(int i= 1;i<= cursize ;i++){
TreeNode node = que.poll();
level.add(node.val);
if(node.left != null){
que.offer(node.left);
}
if(node.right != null){
que.offer(node.right);
}
}
res.add(level);
}
return res;
}}
二叉树的层序遍历->递归实现
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();//存储最后结果
level(root,0,res);
return res;
}
public void level(TreeNode root,int level,List<List<Integer>> res){
if(root == null){
return ;
}
if(res.size() == level){
List<Integer> list = new ArrayList<Integer>();
list.add(root.val);
res.add(list);
}else{
res.get(level).add(root.val);
}
level(root.left, level+1, res);
level(root.right,level+1,res);
}
}
边栏推荐
- The late Apple co-founder Steve Jobs was posthumously awarded the U.S. presidential medal of freedom
- QT smart pointer error prone point
- 二叉树——700.二叉搜索树中的搜索
- SQLZOO——Nobel Quiz
- Seventy second: pedestrian detection
- [learning notes] unreal 4 engine introduction (IV)
- 安全文档归档软件
- sftp和ftp的区别
- 栈与队列——239. 滑动窗口最大值
- How does JS judge whether the current date is within a certain range
猜你喜欢

Sort fake contacts

Zhiniu stock -- 09

A brief introduction to OWASP

栈与队列——239. 滑动窗口最大值

Read the field status of account in ABAP code (hidden, optional, required)

NVIDIA cuDNN学习

arcgis根据矢量范围裁取tif影像(栅格数据)、批量合并shp文件、根据矢量范围裁取区域内的矢量,输出地理坐标系、转换16位TIF影像的像素深度至8位、shp文件创建和矢量框标绘设置

Call nailing API and report an error: the signature sent by the robot is expired; Solution: please keep the signature generation time and sending time within timestampms

Redis extended data type (jump table /bitmaps/hyperloglog/geospatial)

SQLZOO——Nobel Quiz
随机推荐
二叉树——404. 左叶子之和
Exercise (1) create a set C1 to store the elements "one", "two", "three"“
Stm32 systeminit trap during simulation debugging
Prometheus 运维工具 Promtool (二) Query 功能
调用钉钉api报错:机器人发送签名过期;solution:签名生成时间和发送时间请保持在 timestampms 以内
Programming password guessing game
[learning notes] unreal 4 engine introduction (III)
The mobile version of Duoyu security browser will add new functions to make users browse more personalized
Scroll series
What is inode? It will help you understand inode and what help inode provides when creating and deleting files.
BGR and RGB convert each other
The GUI interface of yolov3 (3) -- solve the out of memory problem and add camera detection function
Basic syntax of MySQL DDL, DML and DQL
TOPSIS and entropy weight method
Dead letter queue and message TTL expiration code
Vscode format JSON file
【一库】mapbox-gl!一款开箱即用的地图引擎
BOM browser object model
Song of statistics lyrics
意向不到的Dubug妙招