zoukankan      html  css  js  c++  java
  • [leetcode]Path Sum II

    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]
    ]


    这个问题需要返回每条满足sum值的所有路径。思路是:后序遍历,回溯时将当前node.val添加到左右子树的结果中。

    递归:
    List<List<Int>> path_sum_helper(Treenode node, int current_sum, int depth, int sum_aim):
      if (node is leaf-node):
        r = [[]]
        if (current_sum == sum_aim):
          r_i = []
          r_i[depth] = node.val
          r.add(r_i)
        return r
      else:
        r = [[]]
        if(node.left != null):
          left_ = path_sum_helper(node.left, current_sum + node.left.val, depth + 1, sum_aim)
          if (left_ != null):
            r = left_;
            for(r_ : r):
              r_[level] = node.val
          // similar for right sub-tree
          // need to merge left and right results
        return r


          








  • 相关阅读:
    SpringMvc与Struts2的对比
    Spring 通知
    Spring 之 AOP
    Spring 之 IOC
    Spring IOC 和 AOP概述
    JSON与JAVA数据的相互转换
    (4)-optXXX方法的使用
    (3)-JSONObject的过滤设置
    (2)-生成JSONObject的方法
    String 类型的相关转换
  • 原文地址:https://www.cnblogs.com/luweiseu/p/3143051.html
Copyright © 2011-2022 走看看