Question:
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.
Solution 1:
非常简单的一道题,判断两棵树是否一致,就用层次遍历,每次先判断对应节点值是否相等,再判断结构是否相等,即一棵树有左子树而另一棵没有则为不相等。
/**
* 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) return false;
queue<TreeNode*> pque, qque;
pque.push(p); qque.push(q);
while (!qque.empty() && !pque.empty()) {
// value
TreeNode *pt = pque.front(), *qt = qque.front();
pque.pop(); qque.pop();
if (pt->val != qt->val) return false;
//struct
if (pt->left || qt->left) {
if (pt->left && qt->left) {
pque.push(pt->left); qque.push(qt->left);
} else {
return false;
}
}
if (pt->right || qt->right) {
if (pt->right && qt->right) {
pque.push(pt->right); qque.push(qt->right);
} else {
return false;
}
}
}
return true;
}
};
Solution 2:
想着使用递归做一遍,难点在于判断各种结构情况,判断结构的代码的主要思想是判断是否同时具有左孩子的情况,是否同时具有右孩子的情况,注意到这里面有一些情况是有包含的,代码也已经避免了那些情况,但还是感觉有点冗余。但是速度比上面的解法要快多了。
/**
* 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) return false;
// so p != NULL && q != NULL
if (p->val != q->val) return false;
//judge struct
if (p->left == NULL && q->left == NULL) {
if (p->right == NULL && q->right == NULL) return true;
if (p->right == NULL || q->right == NULL) return false;
return isSameTree(p->right, q->right);
}
if (p->left == NULL || q->left == NULL) return false;
// so p->left != NULL and q->left != NULL
if (p->right == NULL && q->right == NULL)
return isSameTree(p->left, q->left);
if (p->right == NULL || q->right == NULL) return false;
// both left and right exist
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};