Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
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
Note:
Bonus points if you could solve it both recursively and iteratively.
还是使用递归来判断是否镜面对称。比较简单。
先判断根节点,然后调用上题的算法来判断左右子树是否相同。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool sameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL&&q!=NULL)
{
if(p->left==NULL&&p->right==NULL&&q->left==NULL&&q->right==NULL&&p->val==q->val)
return true;
if(p->val!=q->val)
return false;
return sameTree(p->left,q->right)&&sameTree(p->right,q->left);
}
else
return false;
}
bool isSymmetric(struct TreeNode* root) {
if(root==NULL||(root->left==NULL&&root->right==NULL))return true;
if(root->left!=NULL&&root->right!=NULL)
{
return sameTree(root->left,root->right);
}
else
return false;
}