Created
November 21, 2020 23:51
-
-
Save liyunrui/97b78e23088a2645f694ec19365069ea to your computer and use it in GitHub Desktop.
leetcode-bt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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