您的位置:首页 > 其它

101. Symmetric Tree

2016-05-25 11:44 169 查看
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


Note:

Bonus points if you could solve it both recursively and iteratively.

/**
* 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 TreeCmp(TreeNode* p,TreeNode* q)
{
bool b1,b2;
if(!p&&!q)
return true;
else if((!p&&q)||(p&&!q))
return false;
else
{
if(p->val!=q->val)
return false;
else
return TreeCmp(p->left,q->right)&&TreeCmp(p->right,q->left);
}

}
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return TreeCmp(root->left,root->right);

}
};


BFS 迭代

/**
* 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) return true;
stack<TreeNode*> sk;
sk.push(root->left);
sk.push(root->right);

TreeNode* pA, *pB;
while(!sk.empty()) {
pA = sk.top();
sk.pop();
pB = sk.top();
sk.pop();

if(!pA && !pB) continue;
if(!pA || !pB) return false;
if(pA->val != pB->val) return false;

sk.push(pA->left);
sk.push(pB->right);
sk.push(pA->right);
sk.push(pB->left);
}

return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DFS