Binary Tree Paths
1
/ \
2 3
\
5["1->2->5", "1->3"]递归(dfs)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
result = []
if not root:
return result
def dfs(root, path):
if not root.left and not root.right:
result.append(path)
if root.left:
dfs(root.left, path+'->'+str(root.left.val))
if root.right:
dfs(root.right, path+'->'+str(root.right.val))
dfs(root, str(root.val))
return resultDFS+stack:
时间
空间 O(number of leaves)?
Last updated