This commit is contained in:
Sainnhe Park 2023-01-30 20:35:13 +08:00
parent eb1bbfb9c6
commit 2ba7e17b1c
2 changed files with 28 additions and 0 deletions

View File

@ -0,0 +1,11 @@
#ifndef S0101_SYMMETRIC_TREE_HPP
#define S0101_SYMMETRIC_TREE_HPP
#include "structures.hpp"
class S0101 {
public:
bool isSymmetric(TreeNode* root);
};
#endif

View File

@ -0,0 +1,17 @@
#include "s0101_symmetric_tree.hpp"
bool isMirror(TreeNode *root1, TreeNode *root2) {
// 如果都为空指针则互为镜像
if (root1 == nullptr && root2 == nullptr) return true;
// 如果一个是空指针一个不是,则不互为镜像
if (root1 == nullptr || root2 == nullptr) return false;
// 如果根节点的值相等且...则互为镜像
return root1->val == root2->val && isMirror(root1->left, root2->right) &&
isMirror(root1->right, root2->left);
}
bool S0101::isSymmetric(TreeNode *root) {
// 对称树等价于根节点的左子树和右子树互为镜像
if (root == nullptr) return true;
return isMirror(root->left, root->right);
}