fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int data;
  5. TreeNode* left;
  6. TreeNode* right;
  7. TreeNode(int val):left(nullptr),right(nullptr),data(val){};
  8. };
  9.  
  10. vector<vector<int>>level(TreeNode* root){
  11. vector<vector<int>>ans;
  12. queue<TreeNode*>q;
  13. if(root == nullptr){
  14. return ans;
  15. }
  16.  
  17. q.push(root);
  18.  
  19. while(!q.empty()){
  20. int size = q.size();
  21. vector<int>lvl;
  22. for(int i = 0;i< size;i++){
  23. auto u=q.front();q.pop();
  24. lvl.push_back(u->data);
  25. if(u->left){
  26. q.push(u->left);
  27. }
  28.  
  29. if(u->right){
  30. q.push(u->right);
  31. }
  32. }
  33. ans.push_back(lvl);
  34. }
  35. return ans;
  36. }
  37. TreeNode* buildTree(){
  38. int x;cin>>x;
  39. if(x==-1)return nullptr;
  40. TreeNode* root = new TreeNode(x);
  41. queue<TreeNode*>q;
  42. q.push(root);
  43.  
  44. while(!q.empty()){
  45. auto u = q.front();
  46. q.pop();
  47.  
  48. if(cin>>x && x!= -1){
  49. u->left = new TreeNode(x);
  50. q.push(u->left);
  51. }
  52.  
  53. if(cin>>x && x!= -1){
  54. u->right = new TreeNode(x);
  55. q.push(u->right);
  56. }
  57. }
  58. return root;
  59. }
  60. int main() {
  61. TreeNode* root = buildTree();
  62. vector<vector<int>>ans = level(root);
  63. // Clean range-based iteration
  64. for (const auto& lvl : ans) {
  65. for (int val : lvl) {
  66. cout << val << " ";
  67. }
  68. cout << "\n";
  69. }
  70. return 0;
  71. }
Success #stdin #stdout 0.01s 5280KB
stdin
3 9 20 -1 -1 15 7
stdout
3 
9 20 
15 7