
1 分治法-递归
class Solution {
public:
bool recursive(TreeNode* left, TreeNode* right) {
if (!left && !right) return true;
if (!left || !right) return false;
if (left->val == right->val)
return recursive(left->left, right->right) && recursive(left->right, right->left);
return false;
}
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return recursive(root->left, root->right);
}
};

2 迭代法-BFS
class Solution {
public:
bool bfs(TreeNode* left, TreeNode* right) {
if (!left) return true;
queue<TreeNode*> q;
q.push(left);
q.push(right);
while (!q.empty()) {
int sz = q.size();
TreeNode* left_ptr = q.front(); q.pop();
TreeNode* right_ptr = q.front(); q.pop();
if (!left_ptr && !right_ptr) continue;
if (!left_ptr || !right_ptr) return false;
if (left_ptr->val != right_ptr->val) return false;
q.push(left_ptr->left);
q.push(right_ptr->right);
q.push(right_ptr->left);
q.push(left_ptr->right);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return bfs(root, root);
}
};
