当前位置:网站首页>Binary tree related knowledge
Binary tree related knowledge
2022-07-26 00:07:00 【Coding~Man】
1: Sequence traversal of binary tree -> Through the queue while Realization
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;
}}
Sequence traversal of binary tree -> Recursive implementation
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();// Store the final result
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);
}
}
边栏推荐
猜你喜欢

C语言实战之猜拳游戏

YoloV4-tiny网络结构

Binary tree - 404. Sum of left leaves

Android solves the risk of database injection vulnerability

Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK

Leetcode169-多数元素详解

MySQL——多版本并发控制(MVCC)

二叉树——404. 左叶子之和

二叉树——101. 对称二叉树

二叉树——226. 翻转二叉树
随机推荐
BGR and RGB convert each other
你还在用浏览器自带书签?这款书签插件超赞
@The underlying principle of Autowired annotation
What does it mean that the web server stops responding?
Binary tree -- 257. All paths of binary tree
Firewall command simple operation
Binary tree -- 111. Minimum depth of binary tree
Leetcode169 detailed explanation of most elements
BOM 浏览器对象模型
“群魔乱舞”,牛市是不是结束了?2021-05-13
Find the intermediate node of the linked list
Lua script Wireshark plug-in to resolve third-party private protocols
模块二作业
NVIDIA cuDNN学习
Article 75: writing skills of academic papers
Fixed and alternate sequential execution of modes
Backtracking - 17. Letter combinations of phone numbers
Getaverse, a distant bridge to Web3
J9数字论:什么是DAO模式?DAO发展过程的阻碍
STM32 timer