• [leetcode]113. 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.

    Note: A leaf is a node with no children.

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

    题意:

    二叉树之和,返回所有和等于给定值的路径

    思路:

    要穷举所有路径。 backtracking。

    思路类似two sum, 通过(sum - 当前值) 来check 叶子节点的值是否与一路作减法的sum值相等

    代码:

     1 class Solution {
     2       public List<List<Integer>> pathSum(TreeNode root, int sum) {
     3         List<List<Integer>> result = new ArrayList<>();
     4         ArrayList<Integer>  cur = new ArrayList<>(); // 中间结果
     5         helper(root, sum, cur, result);
     6         return result;
     7      }
     8     
     9     
    10     private static void helper(TreeNode root, int sum, ArrayList<Integer> cur,
    11                                 List<List<Integer>> result) {
    12         if (root == null) return;
    13 
    14         cur.add(root.val);
    15 
    16         // leaf node 
    17         if (root.left == null && root.right == null) {
    18             if (sum == root.val)
    19              result.add(new ArrayList<>(cur));
    20         }
    21         
    22         helper(root.left, sum - root.val, cur, result);
    23         helper(root.right, sum - root.val, cur, result);
    24 
    25         cur.remove(cur.size() - 1);
    26     }
    27 }
  • 相关阅读:
    PHP中几种加密形式
    PHP 常用的header头部定义汇总
    php二维数组排序方法(array_multisort,usort)
    js刷新当前页面的几种方法
    chosen.jquery插件的使用
    [NOI2006] 网络收费
    [NOI2002] 贪吃的九头蛇
    [NOI2013] 向量内积
    [TJOI2019] 甲苯先生的线段树
    [CF750G] New Year and Binary Tree Paths
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9158438.html
Copyright © 2020-2023  润新知