'''
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#20ms, 11MB
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root: return []
if not root.left and not root.right: return [str(root.val)]
connector = '->'
self.result = []
def pathstr(root, current):
if not root:
pass
elif not root.left and not root.right:
current += '->'+str(root.val)
self.result.append(current[2:])
else:
current += '->'+str(root.val)
pathstr(root.left, current)
pathstr(root.right, current)
pathstr(root, '')
return self.result
No comments:
Post a Comment