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:
用递归方法,分别判断左右子树是否相同
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
if (NULL == p && NULL == q)
{
return true;
}
else if (NULL != p && NULL != q)
{
if (p->val != q->val)
{
return false;
}
return this->isSameTree(p->left, q->left) && this->isSameTree(p->right, q->right);
}
else
{
return false;
}
}
};