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

  • 相关阅读:
    ASP.NET MVC 页面重定向
    Linux用户管理
    linux开机、重启和用户注销
    vi和vim
    Mac 与 Linux服务器上传下载
    linux 文件体系
    linux 常用命令及异常处理
    单独使用ueditor的图片上传功能,同时获得上传图片地址和缩略图
    mybatis oracle 插入自增记录 获取主键值 写回map参数
    MyBatis SpringMVC映射配置注意
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824982.html
Copyright © 2011-2022 走看看