您的位置:首页 > 其它

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
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));
}

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