Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. // C program for different tree traversals
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. /* A binary tree node has data, pointer to left child
  6. and a pointer to right child */
  7. struct Node
  8. {
  9. int data;
  10. struct Node* left, *right;
  11. Node(int data)
  12. {
  13. this->data = data;
  14. left = right = NULL;
  15. }
  16. };
  17.  
  18. /* Given a binary tree, print its nodes according to the
  19. "bottom-up" postorder traversal. */
  20. void printPostorder(struct Node* node)
  21. {
  22. if (node == NULL)
  23. return;
  24.  
  25. // first recur on left subtree
  26. printPostorder(node->left);
  27.  
  28. // then recur on right subtree
  29. printPostorder(node->right);
  30.  
  31. // now deal with the node
  32. cout << node->data << " ";
  33. }
  34.  
  35. /* Given a binary tree, print its nodes in inorder*/
  36. void printInorder(struct Node* node)
  37. {
  38. if (node == NULL)
  39. return;
  40.  
  41. /* first recur on left child */
  42. printInorder(node->left);
  43.  
  44. /* then print the data of node */
  45. cout << node->data << " ";
  46.  
  47. /* now recur on right child */
  48. printInorder(node->right);
  49. }
  50.  
  51. /* Given a binary tree, print its nodes in preorder*/
  52. void printPreorder(struct Node* node)
  53. {
  54. if (node == NULL)
  55. return;
  56.  
  57. /* first print data of node */
  58. cout << node->data << " ";
  59.  
  60. /* then recur on left sutree */
  61. printPreorder(node->left);
  62.  
  63. /* now recur on right subtree */
  64. printPreorder(node->right);
  65. }
  66.  
  67. /* Driver program to test above functions*/
  68. int main()
  69. {
  70. struct Node *root = new Node(1);
  71. root->left = new Node(2);
  72. root->right = new Node(3);
  73. root->left->left = new Node(4);
  74. root->left->right = new Node(5);
  75.  
  76. cout << "\nPreorder traversal of binary tree is \n";
  77. printPreorder(root);
  78.  
  79. cout << "\nInorder traversal of binary tree is \n";
  80. printInorder(root);
  81.  
  82. cout << "\nPostorder traversal of binary tree is \n";
  83. printPostorder(root);
  84. cout << endl;
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement