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.
思路:
如果两个节点中有一个为空,只需判断两个节点是否全为空,若全为空,返回true;否则,返回false。如果两个节点全为非空,则需判断两个节点的值是否相等,左子树是否相同,右子树是否相同,若三个条件均满足,则返回true;否则,返回false。
Code:
/**
* 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(p==NULL||q==NULL) return (p==q);
return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};