当前位置:网站首页>Skimming records -- sequence traversal of binary tree
Skimming records -- sequence traversal of binary tree
2022-07-28 06:46:00 【HandsomeDog_ L】
Catalog
Title Description : Given a binary tree , Returns the result of its sequence traversal
Title Description : Given a binary tree , Returns the result of its sequence traversal

Combined with auxiliary queue , Two layers of circulation , From top to bottom , Traverse from left to right , The result is sequence traversal
void levelTraverse(TreeNode root) {
if (root == null) return;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
// Traverse every layer of the binary tree from top to bottom
while (!q.isEmpty()) {
int sz = q.size();
// Traverse each node of each layer from left to right
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
// Put the next level node in the queue
if (cur.left != null) {
q.offer(cur.left);
}
if (cur.right != null) {
q.offer(cur.right);
}
}
}
}recursive :
class Solution {
List<List<Integer>> list = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
dns(root,0);
return list;
}
public void dns(TreeNode node,int lever){
if(node == null) return;
if(list.size()==lever) list.add(new ArrayList<Integer>());
list.get(lever).add(node.val);
dns(node.left,lever+1);
dns(node.right,lever+1);
}
}边栏推荐
猜你喜欢

Analysis of the semaphore source code of AQS

Development of Quantitative Trading Robot System

Leetcode skimming diary sword finger offer II 050. sum of downward path nodes

Mongodb quick start

explain详解

Treasure plan TPC system development DAPP construction

Leetcode 刷题日记 剑指 Offer II 055. 二叉搜索树迭代器

Graphic pipeline foundation (I)

【C笔记】数据类型及存储

redis缓存设计与性能优化
随机推荐
SSAO By Computer Shader(三)
Development of clip arbitrage / brick carrying arbitrage system
AQS之ReentrantLock源码解析
【无标题】
费马小定理
Ready to start blogging
AQS之countDownLatch源码分析
NIO示例
mysql索引优化
Treasure plan TPC system development DAPP construction
Code neatness (2)
Water drop effect on umbrella
Leetcode skimming diary sword finger offer II 050. sum of downward path nodes
2022-05-15 based on JWT token
Mongodb replica set and partitioned cluster
Everything you don't know about time complexity is here
Leetcode brush questions diary sword finger offer II 047. Binary tree pruning
Pyppeter drop-down selenium drop-down
浮点型数据在内存中如何存储
[PTA----输出全排列]