题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解题思路:
1.只要pRoot.left和pRoot.right是否对称即可
2.左右节点的值相等且对称子树left.left, right.right ;left.rigth,right.left也对称
参考代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
using namespace std;
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 == NULL)
return false;
return my_isSymmetrical(pRoot,pRoot);
}
bool my_isSymmetrical(TreeNode* pRoot_left,TreeNode* pRoot_right)
{
if (pRoot_left == NULL && pRoot_right == NULL)
return true;
if (pRoot_left == NULL || pRoot_right == NULL)
return false;
if(pRoot_left->val != pRoot_right->val)
return false;
return my_isSymmetrical(pRoot_left->left,pRoot_right->right) && my_isSymmetrical(pRoot_left->right,pRoot_right->left);
}
};
int main() {
Solution solution;
TreeNode TreeNode1(8);
TreeNode TreeNode2(6);
TreeNode TreeNode3(6);
TreeNode TreeNode4(5);
TreeNode TreeNode5(7);
TreeNode TreeNode6(7);
TreeNode TreeNode7(5);
TreeNode1.left = &TreeNode2;
TreeNode1.right = &TreeNode3;
TreeNode2.left = &TreeNode4;
TreeNode2.right = &TreeNode5;
TreeNode3.left = &TreeNode6;
TreeNode3.right = &TreeNode7;
TreeNode4.left = NULL;
TreeNode4.right = NULL;
TreeNode5.left = NULL;
TreeNode5.right = NULL;
TreeNode6.left = NULL;
TreeNode6.right = NULL;
TreeNode7.left = NULL;
TreeNode7.right = NULL;
if (solution.isSymmetrical(&TreeNode1))
cout<<"yes"<<endl;
else
cout<<"fail"<<endl;
return 0;
}
//错误版本
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
//没有考虑left和right为空的情况,而且pRoot为空的时候应该输出为true
if (pRoot != NULL && pRoot->left->val == pRoot->right->val)
return my_isSymmetrical(pRoot->left,pRoot->right);
else
return false;
}
bool my_isSymmetrical(TreeNode* pRoot1,TreeNode* pRoot2)
{
if (pRoot1 == NULL && pRoot2 == NULL)
return true;
if (pRoot1 == NULL && pRoot2 != NULL || pRoot1 != NULL && pRoot2 == NULL)
return false;
if (pRoot1->val != pRoot2->val)
return false;
return my_isSymmetrical(pRoot1->left,pRoot2->right) && my_isSymmetrical(pRoot1->right,pRoot2->left);
}
};
//正确版本
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if (pRoot != NULL)
{
if (pRoot->left != NULL && pRoot->right != NULL)
{
if (pRoot->left->val == pRoot->right->val)
return my_isSymmetrical(pRoot->left,pRoot->right);
else
return false;
} else if (pRoot->left == NULL && pRoot->right == NULL){
return true;
} else{
return false;
}
} else{
return true;
}
}
bool my_isSymmetrical(TreeNode* pRoot1,TreeNode* pRoot2)
{
if (pRoot1 == NULL && pRoot2 == NULL)
return true;
if (pRoot1 == NULL && pRoot2 != NULL || pRoot1 != NULL && pRoot2 == NULL)
return false;
if (pRoot1->val != pRoot2->val)
return false;
return my_isSymmetrical(pRoot1->left,pRoot2->right) && my_isSymmetrical(pRoot1->right,pRoot2->left);
}
};