您的位置:首页 > 其它

101. Symmetric Tree

2017-09-16 12:12 459 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree 
[1,2,2,3,4,4,3]
 is
symmetric:
1
/ \
2   2
/ \ / \
3  4 4  3


But the following 
[1,2,2,null,3,null,3]
 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 isSymmetric(TreeNode* root) {
if(!root){
return true;
}
reverse(root->left);
return __isSymmetric(root->left, root->right);

}

bool __isSymmetric(TreeNode* t1, TreeNode* t2){
if((!t1 && t2) || (t1 && !t2)){
return false;
}

if(!t1 && !t2){
return true;
}

if(t1->val != t2->val){
return false;
}

return __isSymmetric(t1->left, t2->left) && __isSymmetric(t1->right, t2->right);

}

void reverse(TreeNode* root){
if(!root){
return;
}
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
reverse(root->left);
reverse(root->right);
}
};

leetcode上的

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

bool helper(TreeNode* p, TreeNode* q) {
if (!p && !q) {
return true;
} else if (!p || !q) {
return false;
}

if (p->val != q->val) {
return false;
}

return helper(p->left,q->right) && helper(p->right, q->left);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: