fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int val;
  5. vector<TreeNode*>children;
  6. TreeNode(int val):val(val),children({}){};
  7. };
  8.  
  9. void level(TreeNode* root){
  10. if(root == nullptr)return;
  11. queue<TreeNode*>q;
  12. q.push(root);
  13.  
  14. while(!q.empty()){
  15. auto n = q.size();
  16. for(int i = 0 ; i< n;i++){
  17. auto u = q.front();q.pop();
  18.  
  19. cout<<u->val<<",";
  20.  
  21. for(auto child: u->children){
  22. q.push(child);
  23. }
  24. }
  25. cout<<endl;
  26. }
  27.  
  28. }
  29.  
  30. TreeNode* buildTree(vector<int>&arr){
  31. if(arr.empty()||arr[0]==-1){
  32. return nullptr;
  33. }
  34.  
  35. TreeNode* root = new TreeNode(arr[0]);
  36.  
  37. stack<TreeNode*>st;
  38. st.push(root);
  39.  
  40. for(int i = 1 ; i<arr.size();i++){
  41. TreeNode* node = st.top();;
  42.  
  43. if(arr[i]==-1){
  44. st.pop();
  45. }else{
  46. TreeNode* newNode = new TreeNode(arr[i]);
  47. node->children.push_back(newNode);
  48. st.push(newNode);
  49. }
  50. }
  51. return root;
  52. }
  53. void displayTree(TreeNode* root){
  54. if(root == nullptr)return;
  55. if(root)cout<<root->val<<"->";
  56. // if(root->children)cout<<root->children->val<<",";
  57.  
  58. for(auto child: root->children){
  59. cout<<child->val<<",";
  60. }
  61. cout<<endl;
  62. for(auto child: root->children){
  63. displayTree(child);
  64. }
  65.  
  66. }
  67. int main() {
  68. vector<int>arr = {1,2,4,-1,5,-1,-1,3,6,-1,7,-1,-1,-1};
  69. TreeNode* root = buildTree(arr);
  70. displayTree(root);
  71. level(root);
  72. return 0;
  73. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
1->2,3,
2->4,5,
4->
5->
3->6,7,
6->
7->
1,
2,3,
4,5,6,7,