fork download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. struct Node{
  6. int data;
  7. Node *left, *right;
  8. Node (int val) {
  9. data = val;
  10. left = NULL;
  11. right = NULL;
  12. }
  13. };
  14.  
  15. void zigzag(Node *root) {
  16. if(root == NULL) return;
  17.  
  18. stack<Node*> current;
  19. stack<Node*> next;
  20.  
  21. bool leftToRight = true;
  22. current.push(root);
  23.  
  24. while(!current.empty()) {
  25. Node *temp = current.top();
  26. current.pop();
  27.  
  28. if(temp) {
  29. cout << temp->data << " ";
  30.  
  31. if(leftToRight) {
  32. if(temp->left)
  33. next.push(temp->left);
  34. if(temp->right)
  35. next.push(temp->right);
  36. }
  37. else {
  38. if(temp->right)
  39. next.push(temp->right);
  40. if(temp->left)
  41. next.push(temp->left);
  42. }
  43. }
  44. if(current.empty()) {
  45. leftToRight = !leftToRight;
  46. swap(current, next);
  47. }
  48. }
  49. }
  50.  
  51. int main() {
  52. /*
  53.   12
  54.   / \
  55.   9 15
  56.   / \
  57.   5 10
  58.   */
  59. Node *root = new Node(12);
  60. root->left = new Node(9);
  61. root->right = new Node(15);
  62. root->left->left = new Node(5);
  63. root->left->right = new Node(10);
  64.  
  65. zigzag(root);
  66. cout << endl;
  67.  
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
12 15 9 5 10