zoukankan      html  css  js  c++  java
  • LC.113.Path Sum II

    https://leetcode.com/problems/path-sum-ii/description/
    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]
    ]

    难点:
    1: 去哪里建一个LIST 不能每一次循环就建立一个NEW LIST: 我第一次做就是卡在这里了。
    2: helper 返回值是否应该用一个BOOLEAN
    3: 不用考虑走到一半不走了的情况,这道和 PATH SUM 一样,都是走到底:
    root.left == null && root.right == null
    4: ref 的特性: 1)new ArrayList<>(item) 2) 最后-1的原因


     1 public List<List<Integer>> pathSum(TreeNode root, int sum) {
     2         List<List<Integer>> res = new ArrayList<>() ;
     3         //corner case
     4         if (root == null) return res ;
     5         helper(root, sum, res, new ArrayList<>());
     6         return res;
     7     }
     8     /*
     9     需要一个 helper: boolean 只有当下面的返回上来,为TRUE 才把当前的结果加到 RES  中
    10     * */
    11     private void helper(TreeNode root, int sum, List<List<Integer>> res,List<Integer> pathRes){
    12         //corner case: 走到底了
    13         if (root == null) return ;
    14         //PRE-ORDER
    15         int newSum = sum - root.val ;
    16         pathRes.add(root.val) ;
    17         //判断sum是否为零并且当前的root 是否没有叶子了(已经走到底,不用再走了): 这道题是要走到底,不是走一半!
    18         //如果 == 0 说明满足,放进PATH RES 然后返回
    19         if (root.left == null && root.right == null &&newSum ==0 ){
    20             //小心! pathRes IS REF type, 后面的如果对他进行修改,则会改变
    21             res.add(new ArrayList<>(pathRes));
    22             return;
    23         }
    24         //往下面走
    25         if (root.left!=null){
    26             helper(root.left, newSum, res, pathRes) ;
    27             //重点处理! RECURSIVE 是一条道走到黑! 如果先走左边,走到最后一层层返回到这!
    28             //因为你走完了左边 4-11(CURR)-7 现在要去 11的右边 4-11-2 并且用的又是同一个PATHRES,
    29             //所以需要去掉 7 这个点 然后再去右边
    30             pathRes.remove(pathRes.size()-1);
    31         }
    32         if (root.right != null){
    33             helper(root.right,newSum, res, pathRes);
    34             pathRes.remove(pathRes.size()-1);
    35         }
    36     }





  • 相关阅读:
    【持续更新】养成一些好的C++编程习惯,争做一个不让同事骂街的程序员
    Inno Setup界面美化
    QWebengineView页面不实时刷新的问题
    Qt封装窗口进dll须知
    Inno Setup打包工具
    【转载】排序方式整理(带演示GIF)
    MySQL遇见SELECT list is not in GROUP BY clause and contains nonaggre的问题
    JMeter测试TCP协议
    Win10微软拼音关闭Ctrl+Shift+B快捷键
    Hive 窗口函数使用(1)
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8486587.html
Copyright © 2011-2022 走看看