题目:
给定一个二叉树,检查它是否是镜像对称的。
示例:
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
方法一:递归
代码如下:
class Solution
{
public:
bool isSymmetric(TreeNode* root)
{
if (!root) return true;
return mirror(root->left, root->right);
}
bool mirror(TreeNode* p, TreeNode* q)
{
if (!p && !q) return true;
if (!p || !q) return false;
return (p->val == q->val) && mirror(p->left, q->right) && mirror(p->right, q->left);
}
};
运行结果:
方法二:迭代
代码如下:
class Solution
{
public:
bool isSymmetric(TreeNode* root)
{
if (!root) return true;
stack<TreeNode*> tree;
tree.push(root->left);
tree.push(root->right);
while (!tree.empty()) {
TreeNode* p = tree.top();
tree.pop();
TreeNode* q = tree.top();
tree.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
tree.push(p->left);
tree.push(q->right);
tree.push(p->right);
tree.push(q->left);
}
return true;
}
};