您的位置:首页 > 其它

LeetCode--path sum ii

2015-05-26 17:20 344 查看
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]
]

问题描述:给出一个二叉树和整数sum,求和等于sum的所有路径列表。

问题解决:根据path sum问题,对每一个节点,除了维护一个nodes, vals LinkedList聊表外,再加一个路径列表,当和为sum时,将这个节点对应的路径加入结果列表中,当所有路径遍历完毕时,返回结果列表。

解法一:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
LinkedList<Integer> vals = new LinkedList<Integer>();
LinkedList<List<Integer>> lc = new LinkedList<List<Integer>>(); //每个节点保存的路径列表

List<List<Integer>> l = new ArrayList<List<Integer>>();//保存最终结果
List<Integer> temp = new ArrayList<Integer>();

if(root==null)
return null;
nodes.add(root);
vals.add(root.val);
temp.add(root.val);
lc.add(temp);

while(!nodes.isEmpty()){
TreeNode cur = nodes.poll();
int num = vals.poll();
temp = lc.poll();

if((cur.left==null && cur.right==null) && num==sum){
l.add(temp);
}

if(cur.left!=null){
nodes.add(cur.left);
vals.add(num+cur.left.val);
temp.add(cur.left.val);
lc.add(temp);
}
if(cur.right!=null){
nodes.add(cur.right);
vals.add(num+cur.right.val);
temp.add(cur.right.val);
lc.add(temp);
}
}
return l;
}
}


但是这种方法空间。时间开销过大,需要一种新的方法改进。

解法二:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {

List<List<Integer>> res = new ArrayList<List<Integer>>();//保存最终结果
List<Integer> curli = new ArrayList<Integer>();
int curVal = 0;

getPath(root, sum, curVal, res, curli);

return res;
}

public void getPath(TreeNode root, int sum, int curVal,
List<List<Integer>> res, List<Integer> curli) {
// TODO Auto-generated method stub
if(root==null)
return;
curVal += root.val;
curli.add(root.val);
if((root.left==null && root.right==null) && curVal==sum){
res.add(new ArrayList(curli));
return;
}

if(root.left!=null){
getPath(root.left, sum, curVal, res, curli);
curli.remove(curli.size()-1);
}
if(root.right!=null){
getPath(root.right, sum, curVal, res, curli);
curli.remove(curli.size()-1);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: