Binary Tree Paths(dfs,分治)
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3if not root.left and not root.right 错的一塌糊涂!!!!!Last updated
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3if not root.left and not root.right 错的一塌糊涂!!!!!Last updated
# 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