leetcode 113 剑指offer 面试题34. 二叉树中和为某一值的路径(python3)
程序员文章站
2022-07-15 19:41:36
...
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
res = []
self.dfs(root,sum,[],res)
return res
def dfs(self,root,s,li,res):
if root.val == s and not root.left and not root.right:
li.append(root.val)
res.append(li)
s -= root.val
if root.left:
self.dfs(root.left,s,li+[root.val],res)
if root.right:
self.dfs(root.right,s,li+[root.val],res)