leetcode 113 Path Sum II
2016-10-18 22:37
393 查看
采用深度优先与回溯相结合的算法
/**
* 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 LinkedList<List<Integer>>();
List<Integer>curlist=new ArrayList<Integer>();
pathSum(root,sum,res,curlist);
return res;
}
public void pathSum(TreeNode root,int sum,List<List<Integer>>list,List<Integer>curlist){
if(root==null)return;
curlist.add(new Integer(root.val));
if(root.left==null&&root.right==null&&root.val==sum)//叶子节点若满足该条件则为所求的路
{
list.add(new ArrayList(curlist));
curlist.remove(curlist.size()-1);//移除该节点,因为同属于同一个父节点的叶子节点可能与该节点值相同
return;
}
else{
pathSum(root.left,sum-root.val,list,curlist);
pathSum(root.right,sum-root.val,list,curlist);
}
curlist.remove(curlist.size()-1);
}
}
/**
* 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 LinkedList<List<Integer>>();
List<Integer>curlist=new ArrayList<Integer>();
pathSum(root,sum,res,curlist);
return res;
}
public void pathSum(TreeNode root,int sum,List<List<Integer>>list,List<Integer>curlist){
if(root==null)return;
curlist.add(new Integer(root.val));
if(root.left==null&&root.right==null&&root.val==sum)//叶子节点若满足该条件则为所求的路
{
list.add(new ArrayList(curlist));
curlist.remove(curlist.size()-1);//移除该节点,因为同属于同一个父节点的叶子节点可能与该节点值相同
return;
}
else{
pathSum(root.left,sum-root.val,list,curlist);
pathSum(root.right,sum-root.val,list,curlist);
}
curlist.remove(curlist.size()-1);
}
}
相关文章推荐
- LeetCode 113: Path Sum II
- leetcode 113 Path Sum II
- Leetcode[113]-Path Sum II
- LeetCode 113:Path Sum II
- leetcode_question_113 Path Sum II
- [LeetCode 113] Path Sum II
- LeetCode:113 Path Sum II
- LeetCode(113)Path Sum II
- [Leetcode 113, Medium] Path sum II
- [LeetCode 112 113] - 路径和I & II (Path Sum I & II)
- leetcode 113 —— Path Sum II
- LeetCode: Path Sum II [113]
- LeetCode113 Path Sum II
- leetcode——113——Path Sum II
- 【LeetCode】112,113,437. Path Sum I, II, III
- LeetCode 113: Path Sum II 二叉树遍历
- LeetCode113 Path Sum II
- Leetcode 笔记 113 - Path Sum II
- leetcode-113-Path Sum II
- LeetCode(113) Path Sum II