zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    c++ static_cast和dynamic_cast详解
    python 字符串格式化 format
    python zip() 函数
    零零散散的python笔记 2
    PAT 1017
    PAT 1016
    PAT 1015
    Jordan Lecture Note-8: The Sequential Minimal Optimization Algorithm (SMO).
    Jordan Lecture Note-7: Soft Margin SVM
    PAT 1014
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9158438.html
Copyright © 2011-2022 走看看