Skip to content

Instantly share code, notes, and snippets.

@yokolet
Last active September 16, 2018 19:59
Show Gist options
  • Select an option

  • Save yokolet/e4d3cec79f9d7472d573fe2abd313943 to your computer and use it in GitHub Desktop.

Select an option

Save yokolet/e4d3cec79f9d7472d573fe2abd313943 to your computer and use it in GitHub Desktop.
Binary Tree Paths
"""
Description:
Given a binary tree, return all root-to-leaf paths. A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def binaryTreePaths(root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def walk(root, path, result):
path += str(root.val)
if not root.left and not root.right:
result.append(path)
if root.left:
walk(root.left, path+'->', result)
if root.right:
walk(root.right, path+'->', result)
result = []
if not root: return result
walk(root, '', result)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment