题目:
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
思路:
两树同步遍历并判断即可。
代码实现:
/**
* 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 == nullptr && q==nullptr){
return true;
}else if (p == nullptr){
return false;
}else if (q == nullptr){
return false;
}
if (p->val != q->val){
return false;
}
bool left_judge = isSameTree(p->left, q->left);
if (left_judge == false){
return false;
}
bool right_judge = isSameTree(p->right, q->right);
if (right_judge == false){
return false;
}
return true;
}
};
discuss:
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));
}
};