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] ]
思想:用dfs思想求解
注意事项: 对标记节点,要控制回退
java代码:
- ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
- ArrayList<Integer> cur = new ArrayList<Integer>();
- void pathSumHelper(TreeNode root,int sum) {
- if(root==null) return; //注意判断
- cur.add(root.val);
- if(root.left == null && root.right == null) {
- if(root.val == sum) {
- res.add(new ArrayList<Integer>(cur));
- }
- cur.remove(cur.size()-1); //注意回退
- return;
- }
- pathSumHelper(root.left,sum-root.val);
- pathSumHelper(root.right,sum-root.val);
- cur.remove(cur.size()-1); //注意回退
- }
- public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
- if(root==null) return res;
- pathSumHelper(root,sum);
- return res;
- }

浙公网安备 33010602011771号