题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
方法一:
递归
思路:首先根节点以及其左右子树,左子树的左子树和右子树的右子树相同,左子树的右子树和右子树的左子树相同即可
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
bool JudgeComm(TreeNode* left, TreeNode* right) {
if (!left && !right)
return true;
if ((!left && right) || (left && !right))
return false;
if (left->val != right->val)
return false;
else
return JudgeComm(left->left, right->right) && JudgeComm(left->right, right->left);
}
public:
bool isSymmetrical(TreeNode* pRoot)
{
if (!pRoot)
return true;
else
return JudgeComm(pRoot->left, pRoot->right);
}
};
方法二:
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb
来源:牛客网
BFS使用Queue来保存成对的节点
1.出队的时候也是成对成对的
a.若都为空,继续;
b.一个为空,返回false;
c.不为空,比较当前值,值不等,返回false;
2.确定入队顺序,每次入队都是成对成对的;
/*
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)
{
if (!pRoot)
return true;
queue<TreeNode*> nodeQ;
nodeQ.push(pRoot->left);
nodeQ.push(pRoot->right);
while (!nodeQ.empty()) {
TreeNode* currentleft = nodeQ.front();
nodeQ.pop();
TreeNode* currentright = nodeQ.front();
nodeQ.pop();
if(!currentleft && !currentright)
continue;
if(!currentleft || !currentright)
return false;
if (currentleft->val != currentright->val)
return false;
nodeQ.push(currentleft->left);
nodeQ.push(currentright->right);
nodeQ.push(currentleft->right);
nodeQ.push(currentright->left);
}
return true;
}
};
方法三:
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb
来源:牛客网
DFS使用stack来保存成对的节点
1.出栈的时候也是成对成对的 ,
a.若都为空,继续;
b.一个为空,返回false;
c.不为空,比较当前值,值不等,返回false;
2.确定入栈顺序,每次入栈都是成对成对的;
/*
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)
{
if (!pRoot)
return true;
stack<TreeNode*> nodeS;
nodeS.push(pRoot->left);
nodeS.push(pRoot->right);
while (!nodeS.empty()) {
TreeNode* currentleft = nodeS.top();
nodeS.pop();
TreeNode* currentright = nodeS.top();
nodeS.pop();
if(!currentleft && !currentright)
continue;
if(!currentleft || !currentright)
return false;
if (currentleft->val != currentright->val)
return false;
nodeS.push(currentleft->left);
nodeS.push(currentright->right);
nodeS.push(currentleft->right);
nodeS.push(currentright->left);
}
return true;
}
};