bogdanNiculeasa

Traversare arbore

Mar 8th, 2022
598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. struct Node {
  5.     int data;
  6.     struct Node *left, *right;
  7. };
  8.  
  9. Node * newNode(int data) {
  10.     Node * temp  = new Node;
  11.     temp->data = data;
  12.     temp->left = NULL;
  13.     temp->right = NULL;
  14.     return temp;
  15. }
  16.  
  17. // STANGA - RADACINA - DREAPTA (SRD sau inorder)
  18. void printInOrder(struct Node* node) {
  19.     if (node == NULL) {
  20.         return;
  21.     }
  22.  
  23.     // prima oara mergem recursiv pe copilul din stanga
  24.     printInOrder(node->left);
  25.  
  26.     // afisam ce contine nodul
  27.     cout << node->data << " ";
  28.  
  29.     // mergem recursiv pe copilul din dreapta
  30.     printInOrder(node->right);
  31.  
  32. }
  33.  
  34. // Stanga-Dreapta Radacina (SDR postorder)
  35. void printPostOrder(struct Node* node) {
  36.     if (node == NULL) {
  37.         return;
  38.     }
  39.  
  40.     printPostOrder(node->left);
  41.  
  42.     printPostOrder(node->right);
  43.  
  44.     //display the data inside the node
  45.     cout << node->data  << " ";
  46. }
  47. // RADACINA -> STANGA -> DREAPTA (RSD)
  48. void printPreorder(struct Node* node) {
  49.     if (node == NULL) {
  50.         return;
  51.     }
  52.     cout << node->data << " ";
  53.  
  54.     printPreorder(node->left);
  55.  
  56.     printPreorder(node->right);
  57. }
  58.  
  59. int main() {
  60.     std::cout << "Hello, World!" << std::endl;
  61.     struct Node * root = newNode(8);
  62.     root->left = newNode(3);
  63.     root->left->left= newNode(1);
  64.     root->left->right = newNode(6);
  65.     root->left->right->left = newNode(4);
  66.     root->left->right->right = newNode(7);
  67.  
  68.     root->right = newNode(10);
  69.     root->right->right = newNode(14);
  70.     root->right->right->left = newNode(13);
  71.  
  72.     cout << "Postorder tree traverals (STANGA - DREAPTA - RADACINA )"<<endl;
  73.     printPostOrder(root);
  74.  
  75.     cout << "-----------------------------------" << endl;
  76.  
  77.     cout << "Inorder tree traverals (STANGA - RADACINA - DREAPTA )"<<endl;
  78.     printInOrder(root);
  79.  
  80.     cout << "-----------------------------------" << endl;
  81.  
  82.     cout << "Preorder tree traverals (RADACINA -STANGA -  DREAPTA )"<<endl;
  83.     printPreorder(root);
  84.     return 0;
  85. }/**/
  86.  
Advertisement
Add Comment
Please, Sign In to add comment