s0101
This commit is contained in:
parent
eb1bbfb9c6
commit
2ba7e17b1c
11
include/s0101_symmetric_tree.hpp
Normal file
11
include/s0101_symmetric_tree.hpp
Normal 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
|
17
src/s0101_symmetric_tree.cpp
Normal file
17
src/s0101_symmetric_tree.cpp
Normal 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);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user