# 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]
"""
ret = []
if not root:
return ret
self.dfs(root,ret,"")
return list(ret)
def dfs(self,root,ret,path):
if not root.left and not root.right:
path+=str(root.val)
ret.append(path)
return
path+=str(root.val)+"->"
if root.left:
self.dfs(root.left,ret,path)
if root.right:
self.dfs(root.right,ret,path)
# path.pop()
分治:结束返回只考虑自己,往下走分支时候考虑把自己加入子调用。
# 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]
"""
ret = []
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
ret+=[str(root.val)+"->"+i for i in self.binaryTreePaths(root.left)]
ret+=[str(root.val)+"->"+i for i in self.binaryTreePaths(root.right)]
return ret