zoukankan      html  css  js  c++  java
  • 二叉树中和为某一值的路径

    题目描述
    输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的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
    
  • 相关阅读:
    20140830 函数 递归
    函数 20140829
    结构体20140827
    20140826 集合
    20140822数组,应用举例
    140821 字符串,数字,日期及应用举例
    20140819 例子
    HTML基础
    登陆远程服务器
    索引 视图 游标
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/10425903.html
Copyright © 2011-2022 走看看