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.
還是使用遞歸來判斷是否鏡面對稱羞酗。比較簡單懊悯。
先判斷根節(jié)點(diǎn),然后調(diào)用上題的算法來判斷左右子樹是否相同蝶糯。
/**
* 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;
}