力扣题目:二叉树的层序遍历
Posted ACrazyCat的学习记录
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力扣题目:二叉树的层序遍历相关的知识,希望对你有一定的参考价值。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
//分为本层和下一层的遍历队列
queue<TreeNode*> this_level;
queue<TreeNode*> next_level;
//分层存储数据
vector<vector<int> > ans;
vector<int> single_level;
//空树单独处理
if( root == NULL ) return vector<vector<int>>();
//初始化
this_level.push(root);
TreeNode* cur_node;
while( !this_level.empty() ) {
single_level.clear();
//将本层节点输出到结果中
//将本层节点的所有子节点加入下一层队列中
while( !this_level.empty() ) {
cur_node = this_level.front();
single_level.push_back(cur_node->val);
if( cur_node->left != NULL ) {
next_level.push(cur_node->left);
}
if( cur_node->right != NULL ) {
next_level.push(cur_node->right);
}
this_level.pop();
}
ans.push_back(single_level);
//将次层队列换为本层队列
while( !next_level.empty() ) {
this_level.push(next_level.front());
next_level.pop();
}
}
return ans;
}
};
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
//分为本层和下一层的遍历队列
queue<TreeNode*> this_level;
queue<TreeNode*> next_level;
//分层存储数据
vector<vector<int> > ans;
stack<vector<int> > temp_ans;
vector<int> single_level;
//空树单独处理
if( root == NULL ) return vector<vector<int>>();
//初始化
this_level.push(root);
TreeNode* cur_node;
while( !this_level.empty() ) {
single_level.clear();
//将本层节点输出到结果中
//将本层节点的所有子节点加入下一层队列中
while( !this_level.empty() ) {
cur_node = this_level.front();
single_level.push_back(cur_node->val);
if( cur_node->left != NULL ) {
next_level.push(cur_node->left);
}
if( cur_node->right != NULL ) {
next_level.push(cur_node->right);
}
this_level.pop();
}
temp_ans.push(single_level);
//将次层队列换为本层队列
while( !next_level.empty() ) {
this_level.push(next_level.front());
next_level.pop();
}
}
while( !temp_ans.empty() ) {
ans.push_back(temp_ans.top());
temp_ans.pop();
}
return ans;
}
};
以上是关于力扣题目:二叉树的层序遍历的主要内容,如果未能解决你的问题,请参考以下文章
精选力扣500题 第13题 LeetCode 102. 二叉树的层序遍历c++详细题解