代码一
class Solution(object):
# 思路:用前序式DFS,从root到叶子。
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
res = []
return self.pre_DFS(root, res, "")
def pre_DFS(self, root, res, road):
if root:
road += str(root.val)
if not root.left and not root.right:
res.append(road)
else:
road += '->'
self.pre_DFS(root.left, res, road)
self.pre_DFS(root.right, res, road)
return res
代码二
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
pathList = []
if root.left:
pathList += self.binaryTreePaths(root.left)
if root.right:
pathList += self.binaryTreePaths(root.right)
for index, path in enumerate(pathList):
pathList[index] = str(root.val) + "->" + path
return pathList
用list返回二叉树的所有路径。
class Solution(object):
# 前序式DFS——用list返回二叉树的所有路径
# 注意每趟递归前要将当前节点pop()掉
def pre_DFS(self, node, res, road):
# 当前节点为空,直接return
if not node:
return
# 否则将当前节点加入路径中
road.append(node.val)
# 当前节点是叶子则将路径加入外层list中
if not node.left and not node.right:
res.append(list(road))
# 前序式递归当前节点的左右子树
self.pre_DFS(node.left, res, road)
self.pre_DFS(node.right, res, road)
# 每趟递归前将当前节点pop()
road.pop()
# 返回外层list
return res