add: 220319-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-19 02:22:14 +08:00
parent 2de43036d4
commit c14f2873ab
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 32 additions and 1 deletions

31
cpp/2203/220319-CN.cpp Normal file
View File

@ -0,0 +1,31 @@
#include <string>
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {}
};
/**
* 606. Construct String from Binary Tree
* Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
* Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
*/
class Solution {
public:
static std::string tree2str(TreeNode* root) {
if (!root)
return "";
auto ret = std::to_string(root->val);
if (root->left || root->right)
ret += "(" + tree2str(root->left) + ")";
if (root->right)
ret += "(" + tree2str(root->right) + ")";
return ret;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220318-CN.cpp)
ADD_EXECUTABLE(2203 220319-CN.cpp)