链接:
https://leetcode.cn/problems/construct-string-from-binary-tree/
描述:
代码:
代码一:
class Solution {
public:
string tree2str(TreeNode* root) {
if (root == nullptr) return "";
if (root->left == nullptr && root->right == nullptr)
return to_string(root->val);
if (root->right == nullptr) {
return to_string(root->val)
+ "(" + tree2str(root->left) + ")";
}
return to_string(root->val)
+ "(" + tree2str(root->left)
+ ")(" + tree2str(root->right)
+ ")";
}
};
代码二:
class Solution {
public:
string tree2str(TreeNode* root) {
string ret;
if (root == nullptr) return ret;
ret += to_string(root->val);
if (root->left || root->right) {
ret += "(";
ret += tree2str(root->left);
ret += ")";
}
if (root->right) {
ret += "(";
ret += tree2str(root->right);
ret += ")";
}
return ret;
}
};
改进:
代码二问题:拷贝次数太多
class Solution {
public:
void _tree2str(TreeNode* root,string& ret)
{
if (root == nullptr) return;
ret += to_string(root->val);
if (root->left || root->right) {
ret += "(";
_tree2str(root->left,ret);
ret += ")";
}
if (root->right) {
ret += "(";
_tree2str(root->right,ret);
ret += ")";
}
}
string tree2str(TreeNode* root) {
string str;
_tree2str(root,str);
return str;
}
};
代码分析:
采用前序遍历的方式,遍历链表
to_string 可以将数字转化为string