100. Same Tree
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
Constraints:
- The number of nodes in both trees is in the range [0, 100].
- − 1 0 4 < = N o d e . v a l < = 1 0 4 -10^4 <= Node.val <= 10^4 −104<=Node.val<=104
From: LeetCode
Link: 100. Same Tree
Solution:
Ideas:
- Base Cases:
- If both nodes p and q are NULL, then they are obviously the same. We return true.
- If one of the nodes is NULL and the other is not, they aren’t the same, and we return false.
- Recursive Cases:
- If the values of the current nodes p and q are not equal, we return false.
- Otherwise, we recursively check the left subtrees of p and q and the right subtrees of p and q to see if they are the same.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
// If both trees are empty, they are the same
if (p == NULL && q == NULL) return true;
// If one tree is empty and the other is not, they aren't the same
if (p == NULL || q == NULL) return false;
// If the values of the current nodes are different, the trees aren't the same
if (p->val != q->val) return false;
// Recursively check left and right subtrees
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}