题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
判断一棵树是否中轴对称.
Answer 1: iteratively 非递归方法。 树的先序遍历
思路:构造两个队列,分别存储跟结点的左右子树。然后每次对称的判断值是否相等。
Attention:
1. 无论根结点的左右结点是否存在都要push进队列(不存在push(NULL)),这样才能在循环里判断。
LTreeQ.push(root->left);
RTreeQ.push(root->right);
2. 按照对称的结构存储结点. 队列判断值相等时才是正确的。
LTreeQ.push(left->left);
LTreeQ.push(left->right);
RTreeQ.push(right->right);
RTreeQ.push(right->left);
AC Code:
/**
* Definition for binary tree
* 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 == NULL) return true;
queue<TreeNode*> LTreeQ, RTreeQ;
/*
if(root->left) LTreeQ.push(root->left);
if(root->right) RTreeQ.push(root->right);
*/
//无论根结点的左右结点是否存在都要push进队列(不存在push(NULL)),这样才能在循环里判断。
LTreeQ.push(root->left);
RTreeQ.push(root->right);
while(!LTreeQ.empty() && !RTreeQ.empty())
{
TreeNode* left = LTreeQ.front();
LTreeQ.pop();
TreeNode* right = RTreeQ.front();
RTreeQ.pop();
if(left == NULL && right == NULL) continue;
//上面判断了全NULL情况,这句表示其中一个为NULL
if(left == NULL || right == NULL) return false;
if(left->val != right->val) return false;
//按照对称的结构存储结点
LTreeQ.push(left->left);
LTreeQ.push(left->right);
RTreeQ.push(right->right);
RTreeQ.push(right->left);
}
return true;
}
};
Answer 2: recursively 递归方法
思路:递归的判断下一层是否对称。构造递归函数时传入左结点和右结点两个参数。
Attention: 注意要按照对称的判断值传入结点。
AC Code:
/**
* Definition for binary tree
* 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;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode* lt, TreeNode* rt){
if(!lt && !rt) return true;
if(!lt || !rt || lt->val != rt->val) return false;
return isSymmetric(lt->left, rt->right) && isSymmetric(lt->right, rt->left);
}
};