zoukankan      html  css  js  c++  java
  • Binary Tree Path Sum

    Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.

    A valid path is from root node to any of the leaf nodes.

    Example

    Given a binary tree, and target = 5:

         1
        / 
       2   4
      / 
     2   3
    

    return

    [
      [1, 2, 2],
      [1, 4]
    ]
    

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param root the root of binary tree
    15      * @param target an integer
    16      * @return all valid paths
    17      */
    18     public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
    19         // Write your code here
    20         List<List<Integer>> res = new ArrayList<List<Integer>>();
    21         if (root == null){
    22             return res;
    23         }
    24         List<Integer> path = new ArrayList<Integer>();
    25         helper(res, path, root, target);
    26         return res;
    27     }
    28 
    29     private void helper(List<List<Integer>> res, List<Integer> path, TreeNode root, int target){
    30         if (root.left == null && root.right == null){
    31             if (root.val == target) {
    32                 path.add(root.val);
    33                 res.add(new ArrayList<Integer>(path));
    34                 path.remove(path.size() - 1);
    35             }
    36             return;
    37         }
    38         path.add(root.val);
    39         if (root.left != null) {
    40             helper(res, path, root.left, target - root.val);
    41         }
    42         if (root.right != null) {
    43             helper(res, path, root.right, target - root.val);
    44         }
    45         path.remove(path.size() - 1);
    46         return;
    47     }
    48 }
  • 相关阅读:
    Office Shared-Addin : Favorite的下载、安装和使用(2020.2.22)
    VBA编程常用词汇英汉对照表
    Excel-DNA自定义函数的参数智能提示功能:ExcelDna.IntelliSense1.1.0.rar
    VSTO开发中级教程 配套资源下载
    TreeviewEditor.rar
    FaceIDViewer.rar
    imageMso7345.rar
    VisualStudioAddin2016Setup.rar
    VBE2014_Setup_20160709.rar
    documen.write 和 innerHTML 的区别?
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6835851.html
Copyright © 2011-2022 走看看