80. Check if two trees are identical or not

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Example 1:

Input : p = [1, 2, 3] , q = [1, 2, 3]

Output : true

Explanation : Both trees images are shown below

Example 2:

Input : p = [1, 2, 1] , q = [1, 1, 2]

Output : false

Explanation : Both trees images are shown below

Now Your Turn!

Pick the correct output for the given input

Input : p = [5, 1, 2, 8, null, null, 5, null, 4, null, null, 7 ], q = [5, 1, 2, 8, null, null, 4, null, 5, null, null, 7 ]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= Number of Nodes <= 100
  • -104 <= Node.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
//your code goes here
}
};
Test Case

Input:

P
Q