diff --git a/include/s0101_symmetric_tree.hpp b/include/s0101_symmetric_tree.hpp new file mode 100644 index 0000000..95be78f --- /dev/null +++ b/include/s0101_symmetric_tree.hpp @@ -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 diff --git a/src/s0101_symmetric_tree.cpp b/src/s0101_symmetric_tree.cpp new file mode 100644 index 0000000..58102b7 --- /dev/null +++ b/src/s0101_symmetric_tree.cpp @@ -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); +}