52.对称的二叉树
题目内容:
代码及思路:
以上图二叉树为例,如果二叉树是对称的,则满足根节点的第一层左右子树相等,且从第三层开始,左节点的左子树等于右节点的左子树。
#include<iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
class Solution {
public:
void buildtree(TreeNode** root)
{
int temp;
cin >> temp;
if (temp == 0)
{
(*root)->val = 0;
(*root) = nullptr;
return;
}
else
{
(*root)->val = temp;
(*root)->left = new TreeNode;
buildtree(&(*root)->left);
(*root)->right = new TreeNode;
buildtree(&(*root)->right);
}
}
bool isSymmetrical(TreeNode* pRoot)
{
if (pRoot == nullptr)
return true;
return isSymmertical_core(pRoot, pRoot);
}
bool isSymmertical_core(TreeNode* pNode1, TreeNode* pNode2)
{
if (pNode1 == nullptr&&pNode2 == nullptr)
return true;
if (pNode1 == nullptr || pNode2 == nullptr)
return false;
if (pNode1->val != pNode2->val)
return false;
return isSymmertical_core(pNode1->left, pNode2->right) && isSymmertical_core(pNode1->right, pNode2->left);
}
};
int main()
{
Solution* object = new Solution();
TreeNode* root = new TreeNode;
object->buildtree(&root);
bool res = object->isSymmetrical(root);
cout << res << endl;
}