Advertisement
Guest User

Untitled

a guest
Feb 19th, 2012
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node
  6. {
  7.     int data;
  8.     Node *left;
  9.     Node *right;
  10.  
  11.     Node() {;}
  12.     Node(int constData)
  13.     {
  14.         data = constData;
  15.         left = NULL;
  16.         right = NULL;
  17.     }
  18. };
  19.  
  20. void addElement(Node *&root, int myData)
  21. {
  22.     if(root == NULL)
  23.     {
  24.         root = new Node(myData);
  25.         return;
  26.     }
  27.    
  28.     else if(myData < root->data)
  29.         addElement(root->left, myData);
  30.     else
  31.         addElement(root->right, myData);
  32. }
  33.  
  34. void preOrderPrint(Node *root)
  35. {
  36.     if(root != NULL)
  37.     {
  38.         cout << root->data << " ";
  39.         preOrderPrint(root->left);
  40.         preOrderPrint(root->right);
  41.     }
  42. }
  43.  
  44. void postOrderPrint(Node *root)
  45. {
  46.     if(root != NULL)
  47.     {
  48.         preOrderPrint(root->left);
  49.         preOrderPrint(root->right);
  50.         cout << root->data << " ";
  51.     }
  52. }
  53.  
  54. void inOrderPrint(Node *root)
  55. {
  56.     if(root != NULL)
  57.     {
  58.         preOrderPrint(root->left);
  59.         cout << root->data << " ";
  60.         preOrderPrint(root->right);
  61.     }
  62. }
  63.  
  64. int countNodes(Node *root)
  65. {
  66.     if(root == NULL)
  67.     {
  68.         cout << "Empty tree\n";
  69.         return 0;
  70.     }
  71.     else
  72.     {
  73.         static int count = 1;
  74.        
  75.         count += countNodes(root->left);
  76.         count += countNodes(root->right);
  77.  
  78.         return count;
  79.     }
  80. }
  81.  
  82. int main(void)
  83. {
  84.     Node *root;
  85.     root = NULL;
  86.     addElement(root, 100);
  87.     addElement(root, 90;
  88.     addElement(root, 110);
  89.     inOrderPrint(root);
  90.     cout << countNodes(root) << "\n";
  91.     cin.get();
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement