題目描述:
給定一個二叉樹,檢查它是否是鏡像對稱的。
例如,二叉樹 [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) {
if(root==NULL)
return true;
TreeNode *root_l,*root_r,*temp_1,*temp_r;
stack<TreeNode *> sl,sr;
root_l=root->left;
root_r=root->right;
sl.push(root_l);
sr.push(root_r);
while(!sl.empty()&&!sr.empty())
{
root_l=sl.top();
root_r=sr.top();
if(root_l==NULL&&root_r==NULL)
{
sl.pop();
sr.pop();
continue;
}
if(root_l==NULL||root_r==NULL)
return false;
if(root_l->val==root_r->val)
{
sl.pop();
sl.push(root_l->left);
sl.push(root_l->right);
sr.pop();
sr.push(root_r->right);
sr.push(root_r->left);
}
else
return false;
}
return true;
}
};