LeetCode Path Sum II
2014-12-15 23:40
253 查看
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
return
方法2的代码
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:dfs 方法1的代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { class TreeNodePlus { TreeNode node; TreeNodePlus father; TreeNodePlus(TreeNode x,TreeNodePlus f) { node=x; father=f; } } List<List<Integer>> paths = new ArrayList<List<Integer>>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { TreeNodePlus newRoot = new TreeNodePlus(root, null); hasPathSum(newRoot, sum); return paths; } public void hasPathSum(TreeNodePlus root, int sum){ if (root.node == null) { return ; } if (root.node.val==sum && root.node.left==null && root.node.right==null) { ArrayList<Integer> list = new ArrayList<Integer>(); TreeNodePlus father = root; while (father != null) { list.add(0,father.node.val); father = father.father; } paths.add(list); return; } hasPathSum(new TreeNodePlus(root.node.left,root), sum-root.node.val) ; hasPathSum(new TreeNodePlus(root.node.right,root), sum-root.node.val); } }
方法2的代码
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<List<Integer>> paths = new ArrayList<List<Integer>>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { List<Integer> list = new ArrayList<Integer>(); dfs(root, sum, 0, list); return paths; } void dfs(TreeNode root, int sum, int curr, List<Integer> list) { if (root == null) { return; } if (root.left == null && root.right == null) { if (curr + root.val == sum) { list.add(root.val); paths.add(list); } return; } list.add(root.val); dfs(root.left, sum, curr + root.val, new ArrayList<Integer>(list)); dfs(root.right, sum, curr + root.val, new ArrayList<Integer>(list)); } }
相关文章推荐
- [LeetCode] Path Sum II, 关于效率的两个问题: vector还是queue? 传递引用还是拷贝?
- [LeetCode] Path Sum II
- [leetCode刷题笔记]113. Path Sum II
- Leetcode Path Sum II
- Leetcode 113. Path Sum II
- LeetCode Path Sum II
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- LeetCode 112, 123. Path Sum i, ii
- [LeetCode 113] Path Sum II
- LeetCode刷题笔录Path Sum II
- LeetCode-Path Sum II
- [LeetCode] Path Sum II 解题报告
- [LeetCode]Path Sum II
- Path Sum II -- leetcode
- LeetCode 113. Path Sum II(路径和)
- LeetCode | Path Sum II(路径和2)
- [leetcode]113. Path Sum II (medium)
- [Leetcode 113, Medium] Path sum II
- leetcode -- Path Sum II --- 重点,未理解