Code & Func
2018-01-20

第89天。

今天的题目是Binary-Tree-Paths:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1 /
2 3
5

All root-to-leaf paths are:

[“1->2->5”, “1->3”]

比较的简单的题目,直接用递归做就好了,因为python写起来比较简单,所以这里用python实现:

1
def binaryTreePaths(self, root):
2
"""
3
:type root: TreeNode
4
:rtype: List[str]
5
"""
6
self.ret = []
7
if root is None:
8
return self.ret
9
s = []
10
self.binaryTreePathsRec(root,s)
11
return self.ret
12
13
14
def binaryTreePathsRec(self,root,s):
15
if root is None:
8 collapsed lines
16
return
17
s.append(str(root.val))
18
if root.left is None and root.right is None:
19
self.ret.append('->'.join(s))
20
else:
21
self.binaryTreePathsRec(root.left,s)
22
self.binaryTreePathsRec(root.right,s)
23
s.pop()
上一条动态