因为我刷题是难度不是按发布日期,所以就有可能遇到这种情况,比如这个。。。
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
这道题跟之前那道是递进的,而且这道在前,先用它学会怎么判断二叉树相等,然后再去做那道镜像判断。但是呢,我是先把镜像撸出来了,所以这道题就是把之前的题解里面那个子函数拉出来就行。
题解如下:
/**
* Definition for binary tree
* 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 (p == NULL && q == NULL)
{
return true;
}
if (p == NULL || q == NULL)
{
return false;
}
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
就是这样。