Binary Tree Paths
LeetCode 257
DFS
# 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):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.res = []
def dfs(root, path):
if not root.left and not root.right:
self.res.append(path+str(root.val))
if root.left:
# 第二次複習少加了"path" (path+str(root.val)+"->")
# 出來會少個root很神奇
dfs(root.left, path+str(root.val)+"->")
if root.right:
dfs(root.right, path+str(root.val)+"->")
dfs(root,"")
return self.resStack
Last updated