递归与二叉树_leetcode257

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None


# 这是从底向上构建路径
# 从上到下构建路径则需要将path 作为参数传递到下一层 待完成 20190305
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""

res = []
if not root:
return res
if not root.left and not root.right:
res.append(str(root.val))

leftPaths = self.binaryTreePaths(root.left)

for i in range(len(leftPaths)):
res.append(str(root.val) + "->" +leftPaths[i])

rightPaths = self.binaryTreePaths(root.right)
for i in range(len(rightPaths)):
res.append(str(root.val) + "->" + rightPaths[i])

return res
原文地址:https://www.cnblogs.com/lux-ace/p/10546811.html