您的位置:首页 > 其它

Leetcode - Tree - Symmetric Tree

2014-04-29 16:05 405 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

/**
* Definition for binary tree
* 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;
return isEqual(root->left,root->right);
}
bool isEqual(TreeNode *l, TreeNode *r)
{
if(l==NULL&&r==NULL)
return true;
if(l==NULL&&r!=NULL||l!=NULL&&r==NULL)
return false;
if(l->val==r->val&&isEqual(l->left,r->right)&&isEqual(l->right,r->left))
return true;
else
return false;
}
};

/**
* Definition for binary tree
* 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;
stack<TreeNode*> nodeStack;
nodeStack.push(root->left);
nodeStack.push(root->right);
TreeNode *lhs=NULL,*rhs=NULL;
while(nodeStack.size()>1)
{
lhs=nodeStack.top();
nodeStack.pop();
rhs=nodeStack.top();
nodeStack.pop();
if(!lhs&&!rhs) continue;
if((lhs&&!rhs)||(!lhs&&rhs)) return false;
if(lhs->val!=rhs->val)return false;
nodeStack.push(lhs->left);
nodeStack.push(rhs->right);
nodeStack.push(lhs->right);
nodeStack.push(rhs->left);
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: