五. 二叉树 2 Binary Tree Paths
2018-03-05 本文已影响0人
何大炮
思路:
- DFS
注意每个path都应该是独立的,相互之间不存在包含和被包含的关系。
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
self.path = []
if root == None:
return self.path
way = str(root.val)
def dfs(root, way):
if root.left == None and root.right == None:
self.path.append(way)
return
if root.left:
dfs(root.left, way + "->" + str(root.left.val))
if root.right:
dfs(root.right, way + "->" + str(root.right.val))
dfs(root, way)
return self.path