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
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
// If both p and q are null, then they are the same tree
if (p == null && q == null) return true;
// If only one of p and q is null, then they are not the same tree
if (p == null || q == null) return false;
// If the values of p and q are different, then they are not the same tree
if (p.val != q.val) return false;
// Recursively check the left and right subtrees of p and q
// If both the left and right subtrees are the same, then p and q are the same tree
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}