根据二叉树创建字符串
- 题目描述
- 算法分析
- 编程代码
链接: 根据二叉树创建字符串
题目描述
算法分析
当单纯的按照前序遍历输出后,我们只要对()进行一些修改就好
编程代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* root) {
if(root == nullptr)
{
return "";
}
string s = to_string(root->val);
if(root->left == nullptr && root->right || root->left)
{
s += "(";
s+=tree2str(root->left);
s += ")";
}
if(root->right != nullptr)
{
s += "(";
s+=tree2str(root->right);
s += ")";
}
return s;
}
};