Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90737664
Problem-solving ideas:
This question method uses recursive.
-
Prior to the current node p and q be determined non-null, null if both, return true;
-
If a is null, another non-null, then return false;
-
pq are non-null, then compare their val, val if not equal, false;
-
If equal to val, which recursively determines the left and right child nodes are the same.
/**
* 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 && !q) return true;
else if(!p && q || p && !q) return false;
else if(p->val != q->val) return false;
else{
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}
};