Advertisement
Garey

Krisi_Trees

Apr 29th, 2018
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include "stdafx.h"
  2.  
  3. struct elem {
  4.     int key;
  5.     elem* left;
  6.     elem* right;
  7. };
  8.  
  9. bool areIdentical(elem *root1, elem *root2) {
  10.     if (root1 == nullptr && root2 == nullptr)
  11.         return true;
  12.  
  13.     if (root1 == nullptr || root2 == nullptr)
  14.         return false;
  15.  
  16.     return (root1->key == root2->key && areIdentical(root1->left, root2->left) && areIdentical(root1->right, root2->right));
  17. }
  18.  
  19. bool contained(elem *T, elem *S) {
  20.     if (S == nullptr)
  21.         return true;
  22.  
  23.     if (T == nullptr)
  24.         return false;
  25.  
  26.     if (areIdentical(T, S))
  27.         return true;
  28.  
  29.     return contained(T->left, S) ||
  30.         contained(T->right, S);
  31. }
  32.  
  33. elem* addElem(int key) {
  34.     elem* node = new elem;
  35.     node->key = key;
  36.     node->left = NULL;
  37.     node->right = NULL;
  38.     return(node);
  39. }
  40.  
  41. int main() {
  42.     elem *T = addElem(26);
  43.     T->right = addElem(3);
  44.     T->right->right = addElem(3);
  45.     T->left = addElem(10);
  46.     T->left->left = addElem(4);
  47.     T->left->left->right = addElem(30);
  48.     T->left->right = addElem(6);
  49.  
  50.     elem *S = addElem(10);
  51.     S->right = addElem(6);
  52.     S->left = addElem(4);
  53.     S->left->right = addElem(30);
  54.  
  55.     cout << (contained(T, S) ? "Tree 2 is contained in Tree 1\n" : "Tree 2 is not contained in Tree 1\n");
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement