Leetcode笔记 每日一题 606. 根据二叉树创建字符串 (22.03.19)
题目
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例1
> 输入: 二叉树: [1,2,3,4]
1
/ \
2 3
/
4
输出: "1(2(4))(3)"
解释: 原本将是“1(2(4)())(3())”,在你省略所有不必要的空括号对之后,它将是“1(2(4))(3)”。
示例2
> 输入: 二叉树: [1,2,3,null,4]
1
/ \
2 3
\
4
输出: "1(2()(4))(3)"
解释: 和第一个示例相似,除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
思路
[题解重点]:
- 二叉树优先考虑用递归, 将树分为三部分:根节点、左子树、右子树,处理顺序就是根节点->左子树->右子树。
2.由示例可知,输出二叉树节点同时,除根节点以外,在每颗子树左右各加上一个();当左子树为空时,()无法省略;右子树和不存在左右子树时,()可以被省略
[递归算法]
1.如果root不存在,则返回空
2.如果root的左右子树都不存在,则返回当前节点值str(root.val)
3.如果存在左节点不存在右节点,则返回str(root.val)
+递归调用左子树"("+self.tree2str(root.left)+")"
4.如果不存在左节点存在右节点,则需返回str(root.val)+'()'
+递归调用右子树"("+self.tree2str(root.right)+")"
5.如果都存在则返回str(root.val)+"("+self.tree2str(root.left)+")" + "("+self.tree2str(root.right)+")"
复杂度分析:
• 时间复杂度:O(n)
• 空间复杂度:O(n)
代码
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
res =''
if not root: # 判断root是否存在
return res
res += str(root.val)
if not root.left and not root.right: # 判断左右子树是否存在
return res
if root.left and not root.right: # 左子树存在右子树不存情况
res += "("+self.tree2str(root.left)+")"
elif not root.left and root.right: # 左子树不存在右子树存在情况
res += '()'+"("+self.tree2str(root.right)+")"
else: #左右子树都存在
res += "("+self.tree2str(root.left)+")"+"("+self.tree2str(root.right)+")"
return res
Leetcode 606题解热门做法参考
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
if not root:
return ''
res = str(root.val)
if not root.left and not root.right:
return res
left_res = self.tree2str(root.left)
right_res = self.tree2str(root.right)
res += '(' + left_res + ')'
if right_res:
res += '(' + right_res + ')'
return res
---- 附:官方题解以及代码 .提供大家参考