1. 思路
https://www.bilibili.com/video/BV1Nv4y1f74Z
代码
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
res = []
path = []
def findPath(root,target):
if root == None:return
path.append(root.val) # 先序遍历“根”
target -= root.val
if target == 0 and root.left == None and root.right == None:
res.append(path[:]) # 添加path副本,因为path后续还会变
# 如果当前还没找到路径,则2个递归,一个左,一个右
findPath(root.left, target) # 先序遍历“左”
findPath(root.right, target) # 先序遍历“右”
path.pop() # 递归一定先弹出的是左边的结点的值,最后弹出来的是根节点
findPath(root, expectNumber)
return res