Problem :
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example:
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
**
Algorithm:
**
方法1:递归,对左边节点的右子树和右边节点的左子树递归,以及左边节点的左子树和右边节点的右子树递归(因为是对称的)
方法2:非递归,对根节点的左子树,和右子树分别作层次遍历,左子树做从左到右的层次遍历,右子树做从右到左的层次遍历。每次取出两个队列的队首进行比较,要注意的是如果两个节点的对应子树如果一个是空另一个非空,那么就已经说明两个树不是对称的了,如果不管空子树,直接层次遍历,就会出现例子中错误。
**
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
方法1:
class Solution {
public:
bool is(TreeNode* root1,TreeNode* root2)
{
if(root1==NULL&&root2==NULL)
return true;
if(root1==NULL||root2==NULL)
return false;
if(root1->val==root2->val)
{
return is(root1->left,root2->right)&&is(root1->right,root2->left);
}
return false;
}
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
return is(root->left,root->right);
}
};
方法2:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL||(root->left==NULL&&root->right==NULL))
return true;
if((root->left==NULL&&root->right!=NULL)||(root->right==NULL&&root->left!=NULL))
{
return false;
}
queue<TreeNode*> q1;
queue<TreeNode*> q2;
q1.push(root->left);
q2.push(root->right);bool A=true;
while(!q1.empty())
{
TreeNode* t1=q1.front();
TreeNode* t2=q2.front();
q1.pop();
q2.pop();
if(t1->val!=t2->val)
{
A=false;
break;
}
else
{
if((t1->left==NULL&&t2->right!=NULL)||(t1->right==NULL&&t2->left!=NULL))
{
A=false;
break;
}
else
{
if(t1->left)q1.push(t1->left);
if(t1->right)q1.push(t1->right);
if(t2->right)q2.push(t2->right);
if(t2->left)q2.push(t2->left);
}
}
}
return A;
}
};