257.题目描述
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"]
分析
深度优先遍历整棵树,然后使用字符串记录所经过节点的值,当遇到叶节点时,将该字符串加入结果列表。
# 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):
if not root:
return [] #若根为空,返回空列表
res = []
self.dfs(root, "", res) #深度优先搜索,路径为空,res为结果列表
return res
def dfs(self, root, ls, res):
if not root.left and not root.right: #若为叶节点,答案字符串上直接连接叶节点的值,并加入答案列表
res.append(ls+str(root.val))
if root.left: #递归深索左路径
self.dfs(root.left, ls+str(root.val)+"->", res) #更新路径
if root.right: #递归深索右路径
self.dfs(root.right, ls+str(root.val)+"->", res)
113.题目描述
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
分析
深度优先搜索遍历每一个根到叶子节点的路径,
- 使用列表记录所经过的节点值,
- 并且更新加入该节点后,该路径剩余的和。
注意:更新参数target为 target-root.val。
不需要考虑不符合要求的路径要如何处置??不对其进行处理,(不加入返回结果),就是最好的处理。
# 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 pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
res=[]
self.dfs(root,[],res,sum) #空列表记录当前验证的路径,sum记录和
return res
def dfs(self,root,ls,res,rs):
if not root.left and not root.right and rs==root.val:#若是叶子节点,并且值符合要求
ls.append(root.val) #加入返回结果
res.append(ls)
if root.left: #遍历左儿子路径
self.dfs(root.left,ls+[root.val],res,rs-root.val)
if root.right:
self.dfs(root.right,ls+[root.val],res,rs-root.val)
非递归方法
按照中序遍历的思路,访问树中的节点。
注意:
- 如果当前最左节点不是叶节点,下面还有一个右子节点,
- 这时候移动指针时就不能减去当前节点值,
- 为了区分这两种情况,我们需要用一个额外指针pre来指向前一个节点,
- 如果右子节点存在且不等于pre,我们直接将指针移到右子节点,
- 反之,我们更新pre为cur node ,cur node重置为空,sum1减去当前节点,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 pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if root is None:
return
res = []
stack = []
sum1 = 0
node = root
pre = TreeNode(0)
while node or stack:
while node:
stack.append(node)
sum1 += node.val
node = node.left
node = stack[-1]
# 是否符合返回值的条件
if not node.left and not node.right and sum==sum1:
res.append([i.val for i in stack])
# 如果有右节点
if node.right and node.right!=pre:
node = node.right
# 更新pre与其他变量
else:
pre = node
sum1 -= node.val
stack.pop()
node = None
return res