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

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

python solution:

# -*- 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):
        res = []
        if root is None:
            return res
        def search(root,target,temp):
            nonlocal res
            if root.val == target:
                res.append(temp+[root.val])
            if root.left:
                search(root.left,target-root.val,temp+[root.val])
            if root.right:
                search(root.right,target-root.val,temp+[root.val])
        search(root,expectNumber,[])
        return sorted(res,key=lambda x:len(x),reverse=True)

本地测试没有发现问题,然而提交不能通过,猜想是python2的原因?理解不能。

附一个可以通过的答案:

# -*- 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):
        def subFindPath(root):
            if root:
                b.append(root.val)
                if not root.right and not root.left and sum(b) == expectNumber:
                    a.append(b[:])
                else:
                    subFindPath(root.left),subFindPath(root.right)
                b.pop()
        a, b = [], []
        subFindPath(root)
        return a
posted @ 2019-03-02 17:52  bernieloveslife  阅读(122)  评论(0)    收藏  举报