给定一颗二叉树,检查是否镜像对称(围绕中心对称)
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
分析(以下答案有极少的案例未通过,是错误答案!留作分析与纪念):
思路首先:
中序遍历二叉树,再判断遍历结果的对称性
以题目为例子:中序结果3241423,判断序列显然对称
下面那个不对称的例子:23123,判断序列显然不对称
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
if(root){
inorderTraversal(root->left);
result.push_back(root->val);
inorderTraversal(root->right);
}
return result;
}
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
inorderTraversal(root);//获取中序结果
for(int i=0;i<result.size()/2;i++)//判断序列对称否
if(result[i]!=result[result.size()-1-i])
return false;
return true;
}
private:
vector<int> result;
};
经过一段时间的分析才发现:
1),对于二叉树形状太极端情况是无法分辨的,
2),那种本来不是对称二叉树但是他的遍历序列由于数字太巧合却是对称的就不行了!
举例情况1:他的中序遍历为,121,显然不对称
1 \ 2 \ 1
举例情况2:他的中序遍历为,2222,但是显然不对称
2 / \ 2 2 \ 2
错误答案截止
学习别人的答案:
递归,从根节点开始,判断左节点的左子树与右节点的右子树,左节点的右子树与右节点的左子树是否相等即可!
/**
* 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;
return helper(root->left, root->right);
}
//判断节点的左右子树是否对称
bool helper(TreeNode* leftnode, TreeNode* rightnode) {
if (!leftnode && !rightnode) //左右子树均为空
return true;
if (!leftnode || !rightnode) //单子树
return false;
if (leftnode->val != rightnode->val) //左右子树不相等
return false;
//左节点的左子树与右节点的右子树,左节点的右子树与右节点的左子树
return helper(leftnode->left,rightnode->right) && helper(leftnode->right, rightnode->left);
}
};
学习别人的迭代:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
queue<TreeNode*> queue;
if(!root)
return true;
queue.push(root->left);
queue.push(root->right);
TreeNode *leftnode,*rightnode;
while(!queue.empty())
{
leftnode = queue.front();
queue.pop();
rightnode = queue.front();
queue.pop();
if (!leftnode && !rightnode) //左右子树均为空
continue;
if (!leftnode || !rightnode) //单子树
return false;
if(leftnode->val!=rightnode->val)//不相等
return false;
queue.push(leftnode->right);
queue.push(rightnode->left);
queue.push(leftnode->left);
queue.push(rightnode->right);
}
return true;
}
};
小结:
哎.....
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50562771
原作者博客:http://blog.csdn.net/ebowtang