Problem Statement
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 met following two conditions:
- Both tree are structurally identical.
- Each corresponding node on both the trees have the same value.
Example 1:
Given the following two binary trees:
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F63a5ce6edbef8ba7bc31983f%252Fimg%3Aff8503-01cd-011d-4546-66181644c04.jpg%3Fgeneration%3D1671810896750825%26alt%3Dmedia&w=3840&q=75)
Output: true
Explanation: Both trees are structurally identical and have same values.
Example 2:
Given the following two binary trees:
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F63a5ce6edbef8ba7bc31983f%252Fimg%3A76a1160-cac3-888-768c-4a040654b437.jpg%3Fgeneration%3D1671810941966524%26alt%3Dmedia&w=3840&q=75)
Output: false
Explanation: Trees are structurally different.
Example 3:
Given the following two binary trees:
![Image](/_next/image?url=https%3A%2F%2Fstorage.googleapis.com%2Fdownload%2Fstorage%2Fv1%2Fb%2Fdesigngurus-prod.appspot.com%2Fo%2FdocImages%252F63a5ce6edbef8ba7bc31983f%252Fimg%3Ae5c3b11-335-6bb-6df3-e3ee623e4a.jpg%3Fgeneration%3D1671810987707163%26alt%3Dmedia&w=3840&q=75)
Output: false
Explanation: Corresponding nodes have different value ( 4 & 9 ).
Constraints:
- The number of nodes in both trees is in the range
[0, 100]
. - -10<sup>4</sup> <= Node.val <= 10<sup>4</sup>
Try it yourself
Try solving this question here:
Python3
Python3