spider68

tree level order

Mar 12th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. int v[100]={0};
  5. struct Node
  6. {
  7. int data;
  8. struct Node* left, *right;
  9. };
  10. Node* newNode(int data)
  11. {
  12. Node *temp = new Node;
  13. temp->data = data;
  14. temp->left = temp->right = NULL;
  15. return temp;
  16. }
  17. Node* push(Node* head,int z)
  18. {
  19.  
  20. Node*temp=newNode(z);
  21. if(head==NULL){head=temp; return head;}
  22. queue<Node*>q;
  23. Node*x=head;
  24. q.push(head);
  25. while(!q.empty())
  26. {
  27. x=q.front();
  28. if(x->left)q.push(x->left);
  29. else {x->left=temp; return head;}
  30. if(x->right)q.push(x->right);
  31. else {x->right=temp; return head;}
  32. q.pop();
  33. }
  34. return head;
  35. }
  36.  
  37. void travel(Node *root1,int hd)
  38. {
  39. if(root1)
  40. {
  41. v[hd]+=root1->data;
  42. travel(root1->left,hd+1);
  43. travel(root1->right,hd+1);
  44. }
  45. }
  46.  
  47. void print(Node *root)
  48. {
  49. if(root)
  50. {
  51. travel(root,0);
  52. sort(v,v+100);
  53. cout<<v[99];
  54. }
  55. }
  56.  
  57. int main() {
  58. struct Node* root = NULL;
  59. int i,n;
  60. cin>>n;
  61. int a[n];
  62. for(int i=0;i<n;i++)cin>>a[i];
  63. root=push(root,a[i]);
  64. for(int i=1;i<n;i++)push(root,a[i]);
  65. print(root);
  66. return 0;
  67. }
Add Comment
Please, Sign In to add comment