【每日算法】LeetCode 102 —— 二叉树的层序遍历(一百九十四)

题目内容

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例

二叉树:[3,9,20,null,null,15,7],

返回其层序遍历结果:

[
[3],
[9,20],
[15,7]
]

题解

层序遍历需要借助一个队列,然后进行宽度优先搜索即可。

代码

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if(root) q.push(root);

while(q.size()){
vector<int> level;
int len = q.size ();

while(len--){
auto t = q.front();
q.pop();
level.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(level);
}
return res;
}
}
Author: Frederic Niu
Link: https://www.fredericniu.cn/2021/07/17/【每日算法】LeetCode-102-——-二叉树的层序遍历(一百九十四)/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
我的公众号