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

    原题链接在这里:https://leetcode.com/problems/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]
    ]

    题解:

    DFS state needs current node, current sum and target sum, current item and res.

    DFS returns void.

    DFS stop condition when current node is null. Or when current node is leaf.

    If current node node is not null, add current node value and check if it is leaf.

    Note:1. 当res加item时一定要res.add(new ArrayList(item)), 因为list 是 pass by reference, 后面若更改item, 则已经加到res里的item也会同时更改.

    2. Because of 2 return condition, before leaf return, also need to backtrack.

    Time Complexity: O(n), 每个叶子节点都需要检查.

    Space: O(nlogn), 一个item长度是logn, 最多可以有n/2组item, res大小是nlogn, n 是树总共的节点数. 用了logn层stack.

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public List<List<Integer>> pathSum(TreeNode root, int sum) {
    12         List<List<Integer>> res = new ArrayList<>();
    13         if(root == null){
    14             return res;
    15         }
    16         
    17         dfs(root, 0, sum, new ArrayList<Integer>(), res);
    18         return res;
    19     }
    20     
    21     private void dfs(TreeNode root, int cur, int sum, List<Integer> item, List<List<Integer>> res){
    22         if(root == null){
    23             return;
    24         }
    25         
    26         item.add(root.val);
    27         cur += root.val;
    28         if(root.left == null && root.right == null){
    29             if(cur == sum){
    30                 res.add(new ArrayList<Integer>(item));
    31             }
    32             
    33             item.remove(item.size() - 1);
    34             return;
    35         }
    36         dfs(root.left, cur, sum, item, res);
    37         dfs(root.right, cur, sum, item, res);
    38         item.remove(item.size() - 1);
    39     }
    40 }

    类似Path Sum

  • 相关阅读:
    实测好用的awvs批量添加任务脚本
    SQL注入漏洞
    CTF-WEB-信息泄露题目总结
    Awvs+nessus docker版本
    禅道12.4.2后台管理员权限Getshell复现
    子域名工具,使用必应搜索引擎
    i春秋第二届春秋欢乐赛-Web-Hello World
    百度杯CTF比赛 九月场-WEB-题目名称:SQL
    文件上传漏洞
    CVE-2019-17625漏洞复现(Rambox 0.6.9版本存储型XSS)
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824982.html
Copyright © 2011-2022 走看看