您的位置:首页 > 其它

leetcode 113. Path Sum II (路径和) 解题思路和方法

2015-08-22 22:27 447 查看
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]
]


思路:此题与上题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);//一定要删除,确保回溯准确
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: