二叉树中和为某一值的路径

来源:互联网 发布:js只能输入正整数 编辑:程序博客网 时间:2024/06/05 18:43

题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
解法:
递归,先序遍历,用栈保存路径,遍历到根节点求和,等于expect就保存。
注:始终没有AC,但是就是把牛客网说没通过的测试用例本地跑返回的也是正确结果,牛客网返回的错误结果根本不可能得到。想不明白。
更新:想明白了,因为result为类属性,他在进行测试用例时,只生成一个对象,每次测试都使用同一个对象.FindPath(expectNumber),所以始终在对同一个result进行操作,在第一个测试用例使用后,result已经不为空,所以之后的测试用例始终无法通过。

__author__ = 'Zhang Shuai'from functools import reduceclass TreeNode:    def __init__(self, x,left=None,right=None):        self.val = x        self.left = left        self.right = rightclass Solution:    stack = []    result = []    def FindPath(self, root, expectNumber):        if root is None: return self.result        self.stack.append(root.val)        print(self.stack)        sum = reduce(lambda x,y:x+y, self.stack)        if sum == expectNumber and not (root.left or root.right):            self.result.append([i for i in self.stack]) #相当于浅拷贝,如果直接append stack的话相当于把引用添加进去。        self.FindPath(root.left, expectNumber)        self.FindPath(root.right,  expectNumber)        self.stack.pop(-1)        return self.resultroot = TreeNode(10,TreeNode(5,TreeNode(4),TreeNode(7)),TreeNode(12))print(Solution().FindPath(root,15))

解决方法:
使用一个新的函数进行包装,当然也可以再返回的时候把result的复制一个新的list(浅拷贝),然后令list为[]

__author__ = 'Zhang Shuai'from functools import reduceclass Solution:    def FindPath(self, root, expectNumber):        stack = []        result = []        if root is None: return result        return self.findpath(stack,result,root,expectNumber)    def findpath(self,stack,result, root, expectNumber):        if root is None: return        stack.append(root.val)        print(stack)        sum_result = reduce(lambda x, y: x + y, stack)        if sum_result == expectNumber and root.left is None and root.right is None:            result.append([i for i in stack])        self.findpath(stack,result,root.left, expectNumber)        self.findpath(stack,result,root.right, expectNumber)        stack.pop()        return result
原创粉丝点击