http://oj.leetcode.com/problems/same-tree/
思路与上一道求二叉树深度的一样:
1. 检查左右子树是否相同,且p,q节点的值相同
2. 左右子树一个为NULL一个不为NULL时,返回false
/**
* 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) {
bool isSame = true;
if(p == NULL && q != NULL || p != NULL && q == NULL) {
isSame = false;
}else if(p != NULL && q != NULL) {
bool subLeftTree = isSameTree(p->left, q->left);
bool subRightTree = isSameTree(p->right, q->right);
isSame = subLeftTree && subRightTree && (p->val == q->val);
}
return isSame;
}
};