zoukankan      html  css  js  c++  java
  • 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]
    ]

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     ArrayList<ArrayList<Integer>> result = null;
    12     public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
    13         // IMPORTANT: Please reset any member data you declared, as
    14         // the same Solution instance will be reused for each test case.
    15         result = new ArrayList<ArrayList<Integer>>();
    16         check(root, sum, new ArrayList<Integer>());
    17         return result;
    18     }
    19     public void check(TreeNode root, int sum, ArrayList<Integer> row){
    20         if(root == null) return;
    21         row.add(root.val);
    22         sum -= root.val;
    23         if(root.left == null && root.right == null){
    24             if(sum == 0)
    25                 result.add(row);
    26             return;
    27         }
    28         check(root.left , sum, new ArrayList<Integer>(row));
    29         check(root.right, sum, new ArrayList<Integer>(row));
    30     }
    31 }
  • 相关阅读:
    Dapper 基础用法
    测试的分类
    Python
    MySQL数据库的增删改查
    Python面向对象之
    Python面向对象之
    Python
    HTML5/CSS3/JS笔记
    Python-Flask框架之
    Python进程与线程
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426386.html
Copyright © 2011-2022 走看看