Posted on 2023-12-09 00:12
Uriel 阅读(26)
评论(0) 编辑 收藏 引用 所属分类:
搜索 、
数据结构 、
闲来无事重切Leet Code
先序遍历二叉树并且格式化输出,DFS
注意如果只有右子树、左子树为空的话也要输出左子树的一对括号
1 #606
2 #Runtime: 44 ms (Beats 7.3%)
3 #Memory: 16.2 MB (Beats 35.94%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def tree2str(self, root):
13 """
14 :type root: TreeNode
15 :rtype: str
16 """
17 self.ans = ""
18 def DFS(node):
19 self.ans += str(node.val)
20 if node.left or node.right:
21 self.ans += '('
22 if node.left:
23 DFS(node.left)
24 self.ans += ')'
25 if node.right:
26 self.ans += '('
27 DFS(node.right)
28 self.ans += ')'
29
30 if root:
31 DFS(root)
32 return self.ans