当前位置:网站首页>力扣102. 二叉树的层序遍历
力扣102. 二叉树的层序遍历
2022-06-21 16:53:00 【SS_zico】
NC80 bfs
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/er-cha-shu-ceng-xu-bian-li-deng-chang-wo-yao-da-sh/
边栏推荐
猜你喜欢

C语言dll动态链接库

aws elastic beanstalk入门之简介

STM32F1与STM32CubeIDE编程实例-线性霍尔效应传感器驱动

Fishman: telecom customer churn prediction game scheme!

C语言与Lua的交互(实践三)

Stack awareness - stack overflow instance (ret2libc)

智慧三农数字王宁:适合初学者的前5日交易秘诀

Byte traffic business experience: realize as soon as possible, sew money bags, and sell all in goods

Vit is crazy, 10+ visual transformer model details

超分之RLSP
随机推荐
Node的json解析
EtherCAT igh master station controls Esther servo to return to zero
Reids面试题集合 数据结构+穿透雪崩+持久化+内存淘汰策略+数据库双写+哨兵
Typescript的构造方式
信创环境下缓存服务Redis集群部署
科普大佬说 | 如何打造自己的AI创造力?
Postman association to complete interface automation test
postman关联,完成接口自动化测试
I got a pay cut in disguise
谈谈大学两年的学习经历
WXML模板语法、WXSS模板样式、全局配置、页面配置和网络数据请求
基于AM4377的EtherCAT主站控制stm32从站
TypeScript的类型检查
nest.js实战之模块依赖传递性
Gartner 网络研讨会 “九问数字化转型” 会后感
Technical architecture of large websites | information encryption technology and key security management
POSIX create terminate thread
180亿,苏州诞生一个超级母基金
Viewing technological changes through Huawei Corps (IV): interactive media (Music)
Laravel实现文件(图片)上传