【LeetCode】-- 606. 根据二叉树创建字符串

简介: 【LeetCode】-- 606. 根据二叉树创建字符串

1. 题目

给你二叉树的根节点 root ,请你采用前序遍历的方式,将二叉树转化为一个由括号和整数组成的字符串,返回构造出的字符串。

空节点使用一对空括号对 "()" 表示,转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

2. 示例

输入:root = [1,2,3,4]

输出:"1(2(4))(3)"

解释:初步转化后得到 "1(2(4)())(3()())" ,但省略所有不必要的空括号对后,字符串应该是"1(2(4))(3)" 。

3. 分析

1.树的遍历,需要用到递归,考虑递归调用子函数

2.输出字符串,那么就要把树的节点值用to_string( )从整形转为字符串

3.由于的返回值类型是string,每次递归调用都会调拷贝构造函数,需要开空间,拷贝数据,会存在大量的string深拷贝,因此可以考虑用子递归传字符串的引用,就没有了string的深拷贝。

4. 代码实现

1. class Solution {
2. public:
3. 
4. void _tree2str(TreeNode* root,string& str)
5.     {
6. if(root == nullptr)
7.         {
8. return;
9.         }
10. 
11.         str += to_string(root->val);
12. if(root->left || root->right)
13.         {
14.             str += "(";
15.             _tree2str(root->left,str);
16.             str += ")";
17.         }
18. 
19. if(root->right)
20.         {
21.             str += "(";
22.             _tree2str(root->right,str);
23.             str += ")";
24.         }
25. 
26.     }
27. string tree2str(TreeNode* root) {
28.         string s;
29.         _tree2str(root,s);
30. 
31. return s;
32.     }
33. };


相关文章
|
20天前
leetcode代码记录(二叉树的所有路径
leetcode代码记录(二叉树的所有路径
13 0
|
8天前
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
15 0
|
11天前
|
存储 Java
JAVA数据结构刷题 -- 力扣二叉树
JAVA数据结构刷题 -- 力扣二叉树
17 0
|
12天前
[LeetCode]—— 226——翻转二叉树
[LeetCode]—— 226——翻转二叉树
|
12天前
[LeetCode]——965——单值二叉树
[LeetCode]——965——单值二叉树
|
12天前
LeetCode——101——对称二叉树
LeetCode——101——对称二叉树
36 12
|
12天前
|
存储
LeetCode———144—— 二叉树的前序遍历
LeetCode———144—— 二叉树的前序遍历
|
12天前
LeetCode——965. 单值二叉树
LeetCode——965. 单值二叉树
|
14天前
|
算法
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)(下)
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)
7 1
|
14天前
|
算法 C++
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)(上)
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)
7 1