Advertisement
Guest User

Untitled

a guest
May 28th, 2015
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. /* Binary Tree Traversal - Preorder, Inorder, Postorder */
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. struct Node {
  6. char data;
  7. struct Node *left;
  8. struct Node *right;
  9. };
  10.  
  11. //Function to visit nodes in Preorder
  12. void Preorder(struct Node *root) {
  13. // base condition for recursion
  14. // if tree/sub-tree is empty, return and exit
  15. if(root == NULL) return;
  16.  
  17. printf("%c ",root->data); // Print data
  18. Preorder(root->left); // Visit left subtree
  19. Preorder(root->right); // Visit right subtree
  20. }
  21.  
  22. //Function to visit nodes in Inorder
  23. void Inorder(Node *root) {
  24. if(root == NULL) return;
  25.  
  26. Inorder(root->left); //Visit left subtree
  27. printf("%c ",root->data); //Print data
  28. Inorder(root->right); // Visit right subtree
  29. }
  30.  
  31. //Function to visit nodes in Postorder
  32. void Postorder(Node *root) {
  33. if(root == NULL) return;
  34.  
  35. Postorder(root->left); // Visit left subtree
  36. Postorder(root->right); // Visit right subtree
  37. printf("%c ",root->data); // Print data
  38. }
  39.  
  40. // Function to Insert Node in a Binary Search Tree
  41. Node* Insert(Node *root,char data) {
  42. if(root == NULL) {
  43. root = new Node();
  44. root->data = data;
  45. root->left = root->right = NULL;
  46. }
  47. else if(data <= root->data)
  48. root->left = Insert(root->left,data);
  49. else
  50. root->right = Insert(root->right,data);
  51. return root;
  52. }
  53.  
  54. int main() {
  55. /*Code To Test the logic
  56. Creating an example tree
  57. M
  58. / \
  59. B Q
  60. / \ \
  61. A C Z
  62. */
  63. Node* root = NULL;
  64. root = Insert(root,'M'); root = Insert(root,'B');
  65. root = Insert(root,'Q'); root = Insert(root,'Z');
  66. root = Insert(root,'A'); root = Insert(root,'C');
  67. //Print Nodes in Preorder.
  68. cout<<"Preorder: ";
  69. Preorder(root);
  70. cout<<"\n";
  71. //Print Nodes in Inorder
  72. cout<<"Inorder: ";
  73. Inorder(root);
  74. cout<<"\n";
  75. //Print Nodes in Postorder
  76. cout<<"Postorder: ";
  77. Postorder(root);
  78. cout<<"\n";
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement