問題描述:
給定一個二叉樹,檢查它是否是鏡像對稱的。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/symmetric-tree
例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:
1
/ \
2 2
\ \
3 3
解題思路:
遞歸,跟比較倆顆樹是否相同思路一樣,只是有少許區別
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return ismirror(root,root);
}
bool ismirror(TreeNode* p,TreeNode* q){
if(!q && !p) return true;
else if(q && p){
if(q->val!=p->val) return false;
else{
return ismirror(q->left,p->right) && ismirror(q->right,p->left);
}
}
return false;
}
};