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:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false
代码如下:
/**
* 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(p==NULL&&q==NULL)
return true;
else if(p==NULL&&q!=NULL)
return false;
else if(p!=NULL&&q==NULL)
return false;
else if(p!=NULL&&q!=NULL&&p->val!=q->val)
return false;
else
{
return((isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right)));
}
}
最后一条语句之前一定要加return,不然报错warning: control reaches end of non-void function
它的意思是:控制到达非void函数的结尾。就是说你的一些本应带有返回值的函数到达结尾后可能并没有返回任何值。这时候,最好检查一下是否每个控制流都会有返回值。