fork download
  1. //
  2. // main.cpp
  3. // Same Tree
  4. //
  5. // Created by Himanshu on 14/10/21.
  6. //
  7.  
  8.  
  9. #include <iostream>
  10. #include <queue>
  11. using namespace std;
  12.  
  13. struct node {
  14. int info = 0;
  15. struct node *left, *right;
  16. };
  17. typedef struct node Node;
  18.  
  19. node* newNode(int data)
  20. {
  21. node* Node = new node();
  22. Node->info = data;
  23. Node->left = NULL;
  24. Node->right = NULL;
  25.  
  26. return(Node);
  27. }
  28.  
  29. bool checkIfSame(Node *p, Node *q) {
  30. if (p == NULL && q == NULL) {
  31. return true;
  32. } else if (p == NULL || q == NULL) {
  33. return false;
  34. }
  35. if (p->info == q->info && checkIfSame(p->left, q->left) &&
  36. checkIfSame(p->right, q->right)) {
  37. return true;
  38. } else {
  39. return false;
  40. }
  41.  
  42. }
  43.  
  44.  
  45. int main() {
  46. Node *root = newNode(21);
  47. root->left = newNode(30);
  48. root->right = newNode(31);
  49. root->right->left = newNode(40);
  50. root->right->left->right = newNode(51);
  51.  
  52. Node *root1 = newNode(21);
  53. root1->left = newNode(30);
  54. root1->right = newNode(31);
  55. root1->right->left = newNode(40);
  56. root1->right->left->right = newNode(51);
  57.  
  58. Node *root2 = newNode(21);
  59. root2->left = newNode(30);
  60. root2->right = newNode(31);
  61. root2->right->left = newNode(40);
  62. root2->right->left->right = newNode(50);
  63.  
  64. cout<<"Are trees with root (root) and root (root1) are same?"<<endl;
  65. if (checkIfSame(root, root1)) {
  66. cout<<"Trees are same"<<endl;
  67. } else {
  68. cout<<"Trees are not same"<<endl;
  69. }
  70.  
  71. cout<<"Are trees with root (root) and root (root2) are same?"<<endl;
  72. if (checkIfSame(root, root2)) {
  73. cout<<"Trees are same"<<endl;
  74. } else {
  75. cout<<"Trees are not same"<<endl;
  76. }
  77.  
  78. return 0;
  79. }
  80.  
  81.  
Success #stdin #stdout 0s 5636KB
stdin
Standard input is empty
stdout
Are trees with root (root) and root (root1) are same?
Trees are same
Are trees with root (root) and root (root2) are same?
Trees are not same