LintCode Q480 Binary Tree Paths in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2017年2月24日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
# @param {TreeNode} root the root of the binary tree
# @return {List[str]} all root-to-leaf paths
def binaryTreePaths(self, root):
# Write your code here
self.paths = []
if root is None:
return self.paths
def getBinaryTreePaths(root, path):
if root.right is None and root.left is None:
self.paths.append(path)
if root.left:
getBinaryTreePaths(
root.left,
path + '->' + str(root.left.val))
if root.right:
getBinaryTreePaths(
root.right,
path + '->' + str(root.right.val))
getBinaryTreePaths(root, str(root.val))
return self.paths
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。