[LeetCode]113. Path Sum II
2016-02-04 21:29
288 查看
Problem Description
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.[]https://leetcode.com/problems/path-sum-ii/]
思路
就是先根遍历啊啊啊!!一开始因为没想到会出现负数结果超时了啊啊啊!!打开标签发现是DFS啊啊啊!准备重写啊啊啊!!仔细一想不对啊啊啊!!先根和DFS不一样嘛!!!!查了查果然一样啊啊啊!!!基础不牢很方啊啊啊!!!!主要思路就是先根遍历然后剪枝。。。。
Code
package Q113; import java.util.ArrayList; import java.util.List; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public static List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); List<Integer> tmp = new ArrayList<Integer>(); GetPath(root, sum, ans, tmp); return ans; } public static void GetPath(TreeNode root, int sum, List<List<Integer>> ans, List<Integer> tmp) { if (root == null) return; tmp.add(root.val); sum -= root.val; if (sum == 0 && root.right == null && root.left == null) { ans.add(new ArrayList<Integer>(tmp)); tmp.remove(tmp.size() - 1); return; } if (root != null && root.left != null) GetPath(root.left, sum, ans, tmp); if (root != null && root.right != null) GetPath(root.right, sum, ans, tmp); tmp.remove(tmp.size() - 1); } // public static void main(String[] args) { // // TreeNode a = new TreeNode(1); // TreeNode b = new TreeNode(2); // TreeNode c = new TreeNode(3); // a.left = b; // a.right = c; // List<List<Integer>> ans = pathSum(a, 3); // System.out.println(ans.toString()); // // } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解