fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Node{
  5. public:
  6. int data;
  7. Node* left,*right;
  8. Node(int data){
  9. this->data = data;
  10. left=right=NULL;
  11. }
  12. };
  13. void printPreorder(Node* root){
  14. if(!root) return;
  15.  
  16. cout<<root->data<<" ";
  17. printPreorder(root->left);
  18. printPreorder(root->right);
  19. }
  20.  
  21. void printInorder(Node* root){
  22. if(!root) return;
  23.  
  24. printInorder(root->left);
  25. cout<<root->data<<" ";
  26. printInorder(root->right);
  27. }
  28.  
  29. void addbigger(Node* root, int *count){
  30. // we have to do a reverse post order traversal
  31. if(!root) return;
  32.  
  33. addbigger(root->right,count);
  34. root->data = root->data + *count;
  35. *count = root->data;
  36. addbigger(root->left,count);
  37. }
  38.  
  39. int height(Node* root){
  40. if(root==NULL) return 0;
  41.  
  42. return (max(height(root->left),height(root->right))+1);
  43. }
  44.  
  45. void levelorder(Node* root,bool oddeven){
  46. if(!root) return;
  47. Node* temp=NULL;
  48. deque <Node*> dq;
  49. dq.push_front(root);
  50. while(!dq.empty()){
  51. int siz = dq.size();
  52. if(oddeven){
  53. while(siz--){
  54. temp = dq.front();
  55. dq.pop_front();
  56. cout<<temp->data<<" ";
  57. if(temp->left) dq.push_back(temp->left);
  58. if(temp->right) dq.push_back(temp->right);
  59. }
  60. }
  61. else{
  62. while(siz--){
  63. temp = dq.back();
  64. dq.pop_back();
  65. cout<<temp->data<<" ";
  66. if(temp->right) dq.push_front(temp->right);
  67. if(temp->left) dq.push_front(temp->left);
  68. }
  69. }
  70. oddeven= !oddeven;
  71. cout<<endl;
  72. }
  73. return;
  74. }
  75.  
  76. int main() {
  77. Node* root = new Node(3);
  78. root->left = new Node(2);
  79. root->right = new Node(4);
  80. root->left->left = new Node(1);
  81. root->right->right = new Node(5);
  82. root->left->right = new Node(10);
  83. root->right->left = new Node(20);
  84.  
  85. levelorder(root,true);
  86.  
  87.  
  88. return 0;
  89. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
3 
4 2 
1 10 20 5