Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@liyunrui
Created November 21, 2020 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/97b78e23088a2645f694ec19365069ea to your computer and use it in GitHub Desktop.
Save liyunrui/97b78e23088a2645f694ec19365069ea to your computer and use it in GitHub Desktop.
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