- Same Tree
Easy
1262
43
Favorite
Share
Given two binary trees, 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:
Example 2:
Example 3:
C++
bool isSameTree(TreeNode* p, TreeNode* q) {
return DFS(p,q);
}
bool DFS(TreeNode* p,TreeNode* q)
{
if(p == nullptr&&q == nullptr)
return true;
if(p == nullptr||q == nullptr)
return false;
if(p->val != q->val)
return false;
return DFS(p->left,q->left)&&DFS(p->right,q->right);
}