LeetCode刷题(126)~二叉树的层序遍历BFS

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode刷题(126)~二叉树的层序遍历BFS相关的知识,希望对你有一定的参考价值。


题目描述

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

示例:

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

3
/ \\
9 20
/ \\
15 7
返回其层次遍历结果:

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

解答

Demo

vector<vector<int>> levelOrder(TreeNode* root) 
vector<vector<int>> ans;
if(root==NULL)
return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())

int queuesize=q.size();//注意:这里必须先求出队列的长度,后面在for循环中队列长度会动态改变 因为有pop()
ans.push_back(vector<int> ());
for(int i=0;i<queuesize;++i)

TreeNode* temp=q.front();
q.pop();
ans.back().push_back(temp->val);
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);


return ans;

运行结果

LeetCode刷题(126)~二叉树的层序遍历【BFS】_层序遍历

题目来源

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnldjj/
来源:力扣(LeetCode)


以上是关于LeetCode刷题(126)~二叉树的层序遍历BFS的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript 刷题] 搜索 - 二叉树的层序遍历, leetcode 102

刷题-力扣-102. 二叉树的层序遍历

Leetcode刷题100天—107. 二叉树的层序遍历 II(二叉树)—day08

Leetcode刷题100天—102. 二叉树的层序遍历(二叉树)—day09

Leetcode刷题Python102. 二叉树的层序遍历

LeetCode刷题模版:101 - 110