牛客 BM26 求二叉树的层序遍历
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <queue>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> ans;
if(!root) return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int size=q.size();
vector<int> temp;
for(int i=0;i<size;i++)
{
TreeNode* node=q.front();q.pop();
temp.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
ans.push_back(temp);
}
return ans;
}
};
牛客 BM27 按之字形顺序打印二叉树
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <iterator>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > Print(TreeNode* pRoot) {
// write code here
vector<vector<int>> ans;
if(!pRoot) return ans;
queue<TreeNode*> q;
q.push(pRoot);
bool flag=false;
while(!q.empty())
{
int size = q.size();
vector<int> t;
for(int i=0;i<size;i++)
{
auto node = q.front();q.pop();
t.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
if(flag) reverse(t.begin(), t.end());
flag=!flag;
ans.push_back(t);
}
return ans;
}
};