二叉树层序遍历模版
#include "_myPrint.cpp"
#include "_TreeNode.cpp"
#include "stack"
#include "queue"
using namespace std;
class Solution{
public:
vector<vector<int>> levelOrder(TreeNode* root){
vector<vector<int>> res;
queue<TreeNode*> que;
if (root) que.push(root);
while (!que.empty()){
int size = que.size();
vector<int> vec;
for (int i = 0; i < size; i++){
TreeNode* tmp = que.front();
que.pop();
vec.push_back(tmp -> val);
if (tmp -> left) que.push(tmp -> left);
if (tmp -> right) que.push(tmp -> right);
}
res.push_back(vec);
}
return res;
}
};
int main(){
Solution s;
TreeNode* root = new TreeNode(8);
TreeNode* l = new TreeNode(7);
TreeNode* r = new TreeNode(6);
root->left = l;
root->right = r;
vector<vector<int>> res = s.levelOrder(root);
printCollection p;
p.printVecVec(res);
}
#include "vector"
#include "iostream"
#include "vector"
#include "unordered_map"
#include "set"
#include "unordered_set"
#include "string"
using namespace std;
class printCollection{
public:
void printVector(vector<int>& res){
for (int num : res){
cout << num << " ";
}
cout << endl;
}
void printVecVec(vector<vector<int>>& res){
for (vector<int> vec : res){
for (int num : vec){
cout << num << " ";
}
cout << endl;
}
}
void printCharVector(vector<char>& res){
for (char c : res){
cout << c << " ";
}
cout << endl;
}
};