Check if both binary tree are equal

 In this we have to check whether given two trees are equal or not. It is also present in LeetCode.


Question

In this we have to return bool value defining whether both trees are equal or not. Solution of this problem.


Approach

  1.  If both tree has root NULL then simply return true
  2.  If any of the root of tree become NULL return false
  3.  Else pass left & right of root1 & root2. At any step when data mismatch occurs return false. 

#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
  int data;
  Node *right, *left;
};

Node *createNode(int new_data)
{
  Node *new_node = new Node();
  new_node->data = new_data;
  new_node->left = NULL;
  new_node->right = NULL;
  return new_node;
}

int checkEqual(Node *root1, Node *root2)
{
  if(root1 == NULL && root2 == NULL) return 1;
  else if(root1 == NULL && root2 != NULL) return 0;
  else if(root1 != NULL && root2 == NULL) return 0;
  else
  {
    if(root1->data == root2->data &&
      checkEqual(root1->left, root2->left) &&
      checkEqual(root1->right, root2->right))
        return 1;
    else return 0;
  }
}

int main()
{
  Node *root1 = createNode(5);
  Node *root2 = createNode(5);

  root1->left = createNode(9);
  root1->right = createNode(11);
  
  root1->left->left = createNode(15);
  root1->left->right = createNode(19);

  root1->right->left = createNode(18);
  root1->right->right = createNode(21);
  
  if(checkEqual(root1,root2)) cout<<"YES";
  else cout<<"NO";
  
  return 0;
}

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.