题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
#include <iomanip>
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot) {
queue<pair<TreeNode *, TreeNode *>> q;
q.emplace(pRoot, pRoot);
while (!q.empty()) {
auto [l, r] = q.front();
q.pop();
if (!l && !r) {
continue;
}
if (!l || !r || l->val != r->val) {
return false;
}
q.emplace(l->left, r->right);
q.emplace(l->right, r->left);
}
return true;
}
};
思路:迭代。
相当于判断两棵树反转后是否相等,只要将其中一棵树反过来即可。
查看2道真题和解析