您的位置:首页 > 其它

【leetcode】101. Symmetric Tree

2016-06-15 10:50 323 查看
一、题目描述

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.

题目解读:判断一棵树是否对称

思路:用递归的方法

c++代码(8ms,2.62%)

/**
* 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 judge(TreeNode* leftptr, TreeNode* rightptr){
if(leftptr == NULL && rightptr == NULL)
return true;
else if(leftptr == NULL && rightptr != NULL)
return false;
else if(leftptr != NULL && rightptr == NULL)
return false;
else{
if(leftptr -> val == rightptr->val)
return judge(leftptr->left, rightptr->right) && judge(leftptr->right, rightptr->left);
else
return false;
}
}

bool isSymmetric(TreeNode* root) {
if(root == NULL)
return true;
else
return judge(root->left, root->right);

}
};

其他代码,使用队列存储每一行的节点,然后进行比较

代码1(4ms,25.33%):使用两个队列

/**
* 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* leftptr;
TreeNode* rightptr;
queue<TreeNode*> p1,p2;
p1.push(root->left);
p2.push(root->right);
while(!p1.empty() && !p2.empty()){
leftptr = p1.front();
p1.pop();
rightptr = p2.front();
p2.pop();
if(leftptr == NULL && rightptr == NULL)
continue;
if(leftptr == NULL || rightptr == NULL)
return false;
if(leftptr->val != rightptr->val)
return false;
p1.push(leftptr->left);
p1.push(leftptr->right);
p2.push(rightptr->right);
p2.push(rightptr->left);
}
return true;
}
};

代码2(4ms,25.33%):使用一个队列

/**
* 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;
queue<TreeNode*> check;

check.push(root->left);
check.push(root->right);

while (!check.empty()) {
TreeNode* node1 = check.front();
check.pop();
TreeNode* node2 = check.front();
check.pop();
if (!node1 && node2) return false;
if (!node2 && node1) return false;
if (node1 && node2) {
if (node1->val != node2->val) return false;
check.push(node1->left);
check.push(node2->right);
check.push(node1->right);
check.push(node2->left);
}
}

return true;

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