1 分治法-递归
代码语言: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 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
代码语言:javascript
复制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);
}
};