问题描述
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.
题目链接:
思路分析
给出一棵二叉树,判断这颗二叉树是否是对称的。对称的条件是以root所在的位置为对称轴,左右子树的结构和值都相同。一开始想用100. Same Tree的中序遍历树然后对比头尾是否相同的方式解决, 发现这样做会有一些结构上的不同无法发现。
然后现在使用的是递归的方式,检查每一个点是否相同,然后在比较左子结点的左子树与右子结点的右子树,左子结点的右子树与右子结点的左子树是否相同就可以了。
代码
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root != null){
return compare(root.left, root.right);
}
else{
return true;
}
}
private boolean compare(TreeNode p, TreeNode q){
if (p == null && q == null){
return true;
}
else if (p == null || q == null){
return false;
}
else if (p.val != q.val){
return false;
}
else{
return compare(p.left, q.right) && compare(p.right, q.left);
}
}
}
/**
* 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 compare(root->left, root->right);
else
return true;
}
bool compare(TreeNode* p, TreeNode* q){
if (!p && !q)
return true;
else if (!p || !q)
return false;
else if (p->val != q->val)
return false;
else
return (compare(p->left, q->right) && compare(p->right, q->left));
}
};
时间复杂度:O(n) // n为树的结点数
####反思
还是没有掌握递归的精髓,不要总是想着把所有结点都处理完再进行比较,错误代码:
/**
* 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) {
string s = inorderVisitTree(root);
int n = s.length();
for(int i = 0; i < (n/2 + 1); i++){
if(s[i] != s[n-1-i])
return false;
}
return true;
}
string inorderVisitTree(TreeNode* p){
string s = "";
if(p){
if (p->left == NULL && p->right == NULL)
return s += p->val;
if (p->left != NULL)
s += inorderVisitTree(p->left);
else
s += "n";
s += p->val;
if(p->right != NULL)
s += inorderVisitTree(p->right);
else
s += "n";
}
else
return "";
return s;
}
};
。