【剑指Offer】24二叉树中和为某一值的路径

题目描述

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

时间限制:1秒;空间限制:32768K

解题思路

还是递归

# -*- 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
        result = []
        
        def find(root,sum,path=None):
            if path == None:
                path = []
            if not root:
                return []
            path.append(root)
            if root.left == None and root.right == None and root.val == sum:
                onepath = []
                for node in path:
                    onepath.append(node.val)
                result.append(onepath) #记录结果
            else:
                if root.left:
                    find(root.left,sum-root.val,path)
                if root.right:
                    find(root.right,sum-root.val,path)
            path.pop()
            
        find(root, expectNumber)
         
        return result
原文地址:https://www.cnblogs.com/yucen/p/9912036.html