难度:easy
题目描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
题目分析
二叉树遍历(递归和非递归实现)
如果根是空返回true,否则比较根的两个左右子树。
解法1
递归实现
class Solution {
public:
bool judgeSymmetric(TreeNode *left, TreeNode *right) {
if (left == 0 || right == 0) {
if (left == 0 && right == 0)
return true;
else
return false;
}
if (left->val != right->val)
return false;
return judgeSymmetric(left->left, right->right) && judgeSymmetric(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
if (root == 0)
return true;
bool ret = judgeSymmetric(root->left, root->right);
return ret;
}
};
解法2
非递归实现,二叉树的层次遍历,使用辅助队列