leetcode 113. Path Sum II (路径和) 解题思路和方法
2018-01-29 12:13
621 查看
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
思路:此题与上题path 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] ]
思路:此题与上题path sum一脉同源。仅仅是改变了下题目的描写叙述。详细思路是用回溯法,将所有的节点所有遍历。
详细思路和代码例如以下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * 回溯法求解 * 总体思想是遍历。然后加入list逐一试探 * 符合要求的加入结果集 * 不符合要求的删除,然后回溯 */ List<List<Integer>> list = new ArrayList<List<Integer>>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { if(root == null){ return list; } path(root,sum,new ArrayList<Integer>()); return list; } private void path(TreeNode root,int sum, List<Integer> al){ if(root == null){ return; } if(root.val == sum){ if(root.left == null && root.right == null){ al.add(root.val); //加入结果一定要又一次生成实例 list.add(new ArrayList<Integer>(al)); al.remove(al.size()-1);//删除 return; } } al.add(root.val); path(root.left,sum - root.val,al); path(root.right,sum - root.val,al); al.remove(al.size()-1);//一定要删除,确保回溯准确 } }
相关文章推荐
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- Leetcode 113. Path Sum II 路径和2 解题报告
- leetCode 112.Path Sum (路径和) 解题思路和方法
- [LeetCode] 113. Path Sum II 路径和 II
- leetCode 71.Simplify Path(化简路径) 解题思路和方法
- [leetcode] 113. Path Sum II 解题报告
- [LeetCode]113. Path Sum II(列出二叉树根到叶路径和等于sum的所有路径)
- [Leetcode] 113. Path Sum II 解题报告
- 【LeetCode】113.Path Sum II(Medium)解题报告
- leetcode 113. Path Sum II-路径和|回溯算法
- leetCode 63.Unique Paths II (唯一路径II) 解题思路和方法
- LeetCode 113. Path Sum II(路径和)
- 【一天一道LeetCode】#113. Path Sum II
- [Leetcode] Path Sum II路径和
- Leetcode 113. Path Sum II (Medium) (cpp)
- 2017.10.29 LeetCode - 113. Path Sum II【DFS的运用】【补】
- leetCode 52.N-Queens II (n皇后问题II) 解题思路和方法
- LeetCode 113. Path Sum II DFS求解
- LeetCode *** 113. Path Sum II
- [LeetCode] Path Sum II 解题报告