path-sum Java code
2017-10-26 11:28
190 查看
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 andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); if(root == null)return ans; if(root.left == null){ if(root.right == null){ if(root.val != sum)return ans; ArrayList<Integer> list = new ArrayList<Integer>(); list.add(root.val); ans.add(list); return ans; }else{ ArrayList<ArrayList<Integer>> right = pathSum(root.right, sum - root.val); for(ArrayList<Integer> list : right){ list.add(0, root.val); ans.add(list); } return ans; } }else{ if(root.right == null){ ArrayList<ArrayList<Integer>> left = pathSum(root.left, sum - root.val); for(ArrayList<Integer> list : left){ list.add(0, root.val); ans.add(list); } return ans; }else{ ArrayList<ArrayList<Integer>> left = pathSum(root.left, sum - root.val); for(ArrayList<Integer> list : left){ list.add(0, root.val); ans.add(list); } ArrayList<ArrayList<Integer>> right = pathSum(root.right, sum - root.val); for(ArrayList<Integer> list : right){ list.add(0, root.val); ans.add(list); } return ans; } } } }
相关文章推荐
- Leet Code 64 Minimum Path Sum - 最小路径和 - Java
- path-sum Java code
- binary-tree-maximum-path-sum Java code
- Minimum Path Sum (Java)
- leetcode:Path Sum II 【Java】
- [Leetcode] Minimum Path Sum (Java)
- leetocode Path Sum II 2.21 难度系数2
- 【LeetCode-面试算法经典-Java实现】【113-Path Sum II(路径和)】
- Path Sum (Java)
- path-sum python java
- [LeedCode OJ]#64 Minimum Path Sum
- LeetCode Path Sum II in Java
- leetcode JAVA Minimum Path Sum 难度系数3 3.22
- Installing Installation Manager fails with Java exit code 13 when installer path contains special ch
- Combination Sum III Leecode Java
- Leet Code 18 4Sum - 四个数的和等于给定值 - Java
- Path Sum II (Java)
- [LeetCode][Java] Binary Tree Maximum Path Sum
- lintcode 两数之和(Two Sum )(Java)
- Java JsonPath grab InvalidPathException in code, you must be catching Java 7's java.nio.file.InvalidPathException instead of JsonPath's com.jayway.jsonpath.InvalidPathExceptio