您的位置:首页 > 其它

101. Symmetric Tree

2017-01-04 14:47 190 查看

Q

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:



But the following [1,2,2,null,3,null,3] is not:



Note:

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

A

recursively(C)

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
bool judge(struct TreeNode *left, struct TreeNode *right) {
if (left == NULL && right == NULL) {
return true;
}
if (left == NULL || right == NULL) {
return false;
}
if (left->val != right->val) {
return false;
}

return (judge(left->left, right->right) && judge(left->right, right->left));
}

bool isSymmetric(struct TreeNode* root) {
if (root == NULL) {
return true;
}

return judge(root->left, root->right);
}


iteratively(C++)

/**
* 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;
}
if (root->left == NULL && root->right == NULL) {
return true;
}
if (root->left == NULL || root->right == NULL) {
return false;
}

queue<TreeNode *> q1;
queue<TreeNode *> q2;
q1.push(root->left);
q2.push(root->right);
// 每个队列层序遍历
while (!q1.empty() && !q2.empty()) {
TreeNode *l1, *l2;
l1 = q1.front();
l2 = q2.front();
if (l1->val != l2->val) {
return false;
}

if ((l1->left==NULL&&l2->right!=NULL) || (l1->left!=NULL&&l2->right==NULL)) {
return false;
}
if ((l1->right==NULL&&l2->left!=NULL) || (l1->right!=NULL&&l2->left==NULL)) {
return false;
}

if (l1->left!=NULL && l2->right!=NULL) {
q1.push(l1->left);
q2.push(l2->right);
}
if (l1->right!=NULL && l2->left!=NULL) {
q1.push(l1->right);
q2.push(l2->left);
}
q1.pop();
q2.pop();
}

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