Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
这道题给我们一个二叉树,让我们返回所有根到叶节点的路径,跟之前那道Path Sum很类似,比那道稍微简单一些,不需要计算路径和,只需要无脑返回所有的路径即可,那么思路还是用DFS来解
递归(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 result
# 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
return self.dfs(root, str(root.val), result)
def dfs(self, root, path, result):
if not root.left and not root.right:
result.append(path)
if root.left:
self.dfs(root.left, path+'->'+str(root.left.val), result)
if root.right:
self.dfs(root.right, path+'->'+str(root.right.val), result)
return result
DFS+stack:
# 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]
"""
# dfs+stack
if not root:
return []
result = []
stack = [(root, str(root.val))]
while stack:
node, path = stack.pop()
if not node.left and not node.right:
result.append(path)
if node.right:
stack.append((node.right,path+'->'+str(node.right.val)))
if node.left:
stack.append((node.left, path+'->'+str(node.left.val)))
return result
时间
递归:O(n)
空间 O(number of leaves)?
每个 leaf 都代表着一个 path,多少个 leaf 最后就有多少个
Last updated
Was this helpful?