剑指Offer-- 二叉搜索树中和为某一值的路径

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

本身题目不是很难,但是因为刚接触pyhon,对一些对象的传递不太了解,所以跳了很久也没有通过,后来看到 这篇文章  后才明白,犯了一样的错误

# -*- 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 = []             # 存放结果     注意若写成res[[]],那么结果会多出一个[],  
        paths = []           # 存放路径     这里没有使用stack,因为python中列表是可变的,具有stack的功能
        self.helper(root, res, paths, expectNumber)
        return res
     
    def helper(self, root, res, paths, expectNumber):
        if root:                      
            paths.append(root.val)   # 将访问节点的值存入到 路径 列表中
            if (sum(paths) == expectNumber) and (not root.left) and (not root.right):    #  若是 路径 列表中的总和等于给定的数值,那么就将此路径添加到结果中
                res.append(paths[:])      #   注意此处 !! 不是 res.append(paths) 因为python的可变对象都是引用传递
                 
            if root.left:     #   访问左子树
                self.helper(root.left, res, paths, expectNumber)
                
            if root.right:    #   访问右子树
                self.helper(root.right, res, paths, expectNumber)
                
            del paths[-1]   #  每次从子节点返回到父节点时 要删除掉子节点的值

思路就是 :  去考虑前序遍历二叉树,然后在遍历的时候根据题目的要求去做一些判断

在helper函数中,可以大致分为三块,第一块是对于访问到的根节点进行一些操作处理,第二块是访问左子树,第三块是访问右子树,最后别忘了 每次从子节点返回到父节点时,要在路径中删除子节点的值

原文地址:https://www.cnblogs.com/simplepaul/p/7047631.html