zoukankan      html  css  js  c++  java
  • [Leetcode] Binary tree-- 113. Path Sum II

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,
                  5
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    

    return

    [
       [5,4,11,2],
       [5,8,4,5]
    ]
    

    Solution:

     Here I use iterative way,  BFS search

     record the node and the path node value starting from its parent to itself while traversing

     1 if root is None:
     2             return []
     3         
     4         d = []
     5         s = sum
     6         innerLst = [root.val]
     7         ansLst = []
     8         d.append((root, innerLst))
     9         while (len(d)):
    10             nodeInfo = d.pop(0)
    11             node = nodeInfo[0]
    12             innerLst = nodeInfo[1]
    13             if not node.left and not node.right:
    14                 #print ("innerLst: ", innerLst, s, type(innerLst))
    15                 #sumPath = sum(innerLst)
    16                 sumPath = 0
    17                 for e in innerLst:
    18                     sumPath+=e
    19                 if sumPath == s:
    20                     ansLst.append(innerLst)
    21             if node.left:
    22                 d.append((node.left, innerLst + [node.left.val]))
    23             if node.right:
    24                 d.append((node.right, innerLst + [node.right.val]))
    25         return ansLst
     
  • 相关阅读:
    CDQ分治
    [noip模拟赛2017.7.15]
    [noip模拟赛2017.7.11]
    [noip模拟赛2017.7.10]
    [noip模拟赛2017.7.7]
    [noip模拟赛2017.7.6]
    [noip模拟赛2017.7.4]
    回文检测
    mapreduce引用第三方jar
    Spark安装和配置
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7257572.html
Copyright © 2011-2022 走看看