LeetCode 606. 【递归】根据二叉树创建字符串
原题链接
简单
作者:
大明湖的鱼
,
2021-01-24 15:06:13
,
所有人可见
,
阅读 240
注意
- 字符串拼接算法效率很低
- 根节点外不需要包裹
- 题意是如果左子树为空的话用()代替,右子树为空不用管。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* t) {
string res= "";
if(t == nullptr) return res;
if(t->left == nullptr && t->right == nullptr){
res.append(to_string(t->val));
return res;
}
res.append(to_string(t->val));
res+=("(" + tree2str(t->left) + ")");
if(t->right != nullptr) res+=("(" + tree2str(t->right) + ")");
return res;
}
};