fork download
  1. //
  2. // main.cpp
  3. // Depth First Traversal in Binary Tree
  4. //
  5. // Created by Himanshu on 26/08/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <queue>
  10. using namespace std;
  11.  
  12. struct node {
  13. int value = 0;
  14. struct node *left, *right;
  15. };
  16. typedef struct node Node;
  17.  
  18. node* newNode(int data)
  19. {
  20. node* Node = new node();
  21. Node->value = data;
  22. Node->left = NULL;
  23. Node->right = NULL;
  24.  
  25. return(Node);
  26. }
  27.  
  28. void inorder (Node *root) {
  29. if (root == NULL) {
  30. return;
  31. }
  32.  
  33. // traverse left
  34. inorder (root->left);
  35.  
  36. // print root
  37. cout << root->value << " ";
  38.  
  39. // traverse right
  40. inorder (root->right);
  41. }
  42.  
  43. void preorder (Node *root) {
  44. if (root == NULL) {
  45. return;
  46. }
  47.  
  48. // print root
  49. cout << root->value << " ";
  50.  
  51. // traverse left
  52. preorder (root->left);
  53.  
  54. // traverse right
  55. preorder (root->right);
  56. }
  57.  
  58. void postorder (Node *root) {
  59. if (root == NULL) {
  60. return;
  61. }
  62.  
  63. // traverse left
  64. postorder (root->left);
  65.  
  66. // traverse right
  67. postorder (root->right);
  68.  
  69. // print root
  70. cout << root->value << " ";
  71. }
  72.  
  73. int main() {
  74. Node *root = newNode(1);
  75. root->left = newNode(2);
  76. root->right = newNode(3);
  77. root->right->left = newNode(4);
  78. root->right->right = newNode(5);
  79.  
  80. cout<<"Inorder traversal:"<<endl;
  81. inorder (root);
  82. cout<<endl;
  83.  
  84. cout<<"Preorder traversal:"<<endl;
  85. preorder (root);
  86. cout<<endl;
  87.  
  88. cout<<"Postorder traversal:"<<endl;
  89. postorder (root);
  90. cout<<endl;
  91.  
  92. return 0;
  93. }
Success #stdin #stdout 0.01s 5388KB
stdin
Standard input is empty
stdout
Inorder traversal:
2 1 4 3 5 
Preorder traversal:
1 2 3 4 5 
Postorder traversal:
2 4 5 3 1