題目:
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
分析:
題目是要判斷左右兩顆子樹是否對稱,採用只要根節點的值相同,並且左邊子樹的左子樹和右邊子樹餓右子樹對稱 且 左邊子樹的右子樹和右邊子樹的左子樹對稱。採用樹的遍歷的思想,遞歸的解決該問題。
代碼:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL||(root->left==NULL&&root->right==NULL))
return true;
return postorder(root->left,root->right);
}
bool postorder(TreeNode* p,TreeNode* q)
{
if(p&&q)
{
if(p->val!=q->val)
return false;
return postorder(p->left,q->right)&&postorder(p->right,q->left);
}else if(p==NULL&&q==NULL)
return true;
else
return false;
}
};