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


          








  • 相关阅读:
    echarts各个配置项详细说明总结
    享元模式
    观察者模式
    策略模式
    桥接模式
    适配器模式
    建造者模式
    原型模式
    单例模式
    Java8新特性——集合底层源码实现的改变
  • 原文地址:https://www.cnblogs.com/luweiseu/p/3143051.html
Copyright © 2011-2022 走看看