1 DFS
代码语言:javascript
复制/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q) return true;
if (!p || !q) return false;
if (p->val == q->val)
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
return false;
}
};
2 BFS
代码语言:javascript
复制class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q) return true;
if (!p || !q) return false;
queue<TreeNode*> pp, qq;
pp.push(p);
qq.push(q);
while(!qq.empty()) {
TreeNode* p_node = pp.front(); pp.pop();
TreeNode* q_node = qq.front(); qq.pop();
if (p_node->val != q_node->val) return false;
if ((!p_node->left && q_node->left) || (p_node->left && !q_node->left) ||(!p_node->right && q_node->right) || (p_node->right && !q_node->right))
return false;
if (p_node->left && q_node->left) {
pp.push(p_node->left);
qq.push(q_node->left);
}
if (p_node->right && q_node->right) {
pp.push(p_node->right);
qq.push(q_node->right);
}
}
return true;
}
};