题目:
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
方法一:
采用递归,根节点以及其左右子树,左子树的左子树和右子树的右子树相同,左子树的右子树和右子树的左子树相同即可,
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
return isSys(pRoot,pRoot);
}
private:
bool isSys(TreeNode* pRoot1,TreeNode* pRoot2)
{
if(pRoot1==NULL&&pRoot2==NULL)
return true;
else if(pRoot1==NULL||pRoot2==NULL)
return false;
else if(pRoot1->val!=pRoot2->val)
return false;
return isSys(pRoot1->left,pRoot2->right) && isSys(pRoot1->right,pRoot2->left);
}
};
方法二:
采用层次遍历,分为先左后右和先右后左两种方法,只要两次结果相等就说明这棵树是一颗对称二叉树。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
queue<TreeNode*>tree1;
queue<TreeNode*>tree2;
tree1.push(pRoot);
tree2.push(pRoot);
while(!tree1.empty() && !tree2.empty())
{
TreeNode*front1=tree1.front();
TreeNode*front2=tree2.front();
tree1.pop();
tree2.pop();
if(front1==NULL&&front2==NULL) //两边都是空
continue;
if(front1==NULL||front2==NULL) //一边为空
return false;
if(front1->val!=front2->val)
return false;
tree1.push(front1->left);
tree1.push(front1->right);
tree2.push(front2->right);
tree2.push(front2->left);
}
return true; //遍历完成才知道是不是左右对称
}
};
本文介绍两种方法判断二叉树是否对称:一是递归比较左右子树及其镜像;二是通过层次遍历检查每层节点是否满足对称条件。
1998

被折叠的 条评论
为什么被折叠?



