题目描述:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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;
}
};
执行效率:
执行用时:8 ms, 在所有 C++ 提交中击败了48.44%的用户
内存消耗:13.1 MB, 在所有 C++ 提交中击败了100.00%的用户