101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
- 递归解法
/**
* 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 helper(TreeNode *p, TreeNode *q) {
if (p == NULL && q == NULL) return true;
if (p == NULL || q == NULL) return false;
return p->val == q->val && helper(p->left, q->right) && helper(p->right, q->left);
}
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return helper(root->left, root->right);
}
};
- 迭代解法
/**
* 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 isSymmetric(TreeNode* root) {
if (!root) return true;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
vector<int> tmp;
for (int i = q.size(); i > 0; --i) {
TreeNode *t = q.front(); q.pop();
if (t != NULL) {
tmp.push_back(t->val);
q.push(t->left);
q.push(t->right);
} else {
tmp.push_back(INT_MAX);
}
}
int k = 0, m = tmp.size() - 1;
while (k < m) {
if (tmp[k++] != tmp[m--]) return false;
}
}
return true;
}
};