https://leetcode.com/problems/same-tree/
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.
比较两棵二叉树是否结构、数据均相等:1)若均为空则相等;
2)其中一棵为空、另一棵非空,或者数据不同,则不相等;
3)递归比较左子树和右子树是否均相等;
/**
* 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 true;
if(p==NULL || q==NULL || p->val != q->val)
return false;
bool leftFlag = isSameTree(p->left,q->left);
bool rightFlag = isSameTree(p->right,q->right);
return leftFlag && rightFlag;
}
};