diff --git a/cpp/2205/220524-CN.cpp b/cpp/2205/220524-CN.cpp new file mode 100644 index 0000000..4d46c4c --- /dev/null +++ b/cpp/2205/220524-CN.cpp @@ -0,0 +1,27 @@ +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x = 0, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(x), left(l), right(r) {} +}; + +/** + * 965. Univalued Binary Tree + * A binary tree is uni-valued if every node in the tree has the same value. + * Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise. + */ + +class Solution { +public: + static bool isUnivalTree(TreeNode* root) { + if (!root) + return true; + std::function dfs = [&](const TreeNode* ptr) { + return !ptr || (ptr->val == root->val && dfs(ptr->left) && dfs(ptr->right)); + }; + return dfs(root->left) && dfs(root->right); + } +}; diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index 4f8c1e4..0ca418f 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220523.cpp) +ADD_EXECUTABLE(2205 220524-CN.cpp)