算法分析与设计作业题
作业来源
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.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
bool sameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL&&q!=NULL)
{
if(p->left==NULL&&p->right==NULL&&q->left==NULL&&q->right==NULL&&p- >val==q->val)
return true;
if(p->val!=q->val)
return false;
return sameTree(p->left,q->left)&&sameTree(p->right,q->right);
}
else
return false;
}
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
return sameTree(p,q);
}
};