Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
leetcode-bt
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
def dfs(root, path = []):
if root:
if not root.right and not root.left:
res.append(path + [root.val])
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root,[])
return ["->".join([str(n) for n in path]) for path in res]
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
all_paths = []
def dfs(r, path = []):
if not r:
return
if not r.left and not r.right:
all_paths.append(path+[r.val])
dfs(r.left, path + [r.val])
dfs(r.right, path + [r.val])
dfs(root, [])
return ["->".join([str(n) for n in path]) for path in all_paths]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment