Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
先序遍历二叉树并且格式化输出,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

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理