
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Same Tree in C++
Suppose we have two binary trees; we have to define a function to check whether they are the same or not. We know that the binary trees are considered the same when they are structurally identical and the nodes have the same value.
So, if the input is like [1,2,3],[1,2,3], then the output will be True
To solve this, we will follow these steps −
Define a function called isSameTree, this will take two tree nodes p and q
-
if p is the same as NULL and q is same as NULL, then −
return true
-
if p is the same as NULL or q is same as NULL, then −
return false
-
if val of p is the same as val of p and isSameTree(left of p, left of q) is true and isSameTree(right of p, right of q) is true, then
return true
return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; } else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; } else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } class Solution { public: bool isSameTree(TreeNode *p, TreeNode* q){ if (p == NULL && q == NULL) return true; if (p == NULL || q == NULL) return false; if (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) return true; return false; } }; main(){ Solution ob; vector<int> v = {1,2,3}, v1 = {1,2,3}; TreeNode *root1 = make_tree(v); TreeNode *root2 = make_tree(v1); cout << (ob.isSameTree(root1, root2)); }
Input
{1,2,3}, {1,2,3}
Output
1