leetCode113题,路径和
使用 回溯算法:
思路:使用dfs,递归进入当前节点,记录节点的值,如果层数达到了,就查看记录是否和目标值相等,如果相等,就把 局部链表 l 深拷贝就 g链表里面,这时,返回上一层是记得要把 l链表记录的当前节点抹除掉,这要就成功回溯到了上一层
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int sum;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
this.sum = sum;
LinkedList<List<Integer>> g = new LinkedList();
LinkedList<Integer> l = new LinkedList();
dfs(g,l,root,0);
return g;
}
public void dfs(List<List<Integer>> g,LinkedList<Integer>l,TreeNode root,int curSum) {
if(root==null) return;
boolean bl = root.left==null;
boolean br = root.right == null;
curSum += root.val;
l.add(root.val);
if(bl&&br) {
if(curSum == this.sum) {
List<Integer> ans = new LinkedList(l);
g.add(ans);
//记得要回溯
l.removeLast();
return;
}
}
if(!bl) {
dfs(g,l,root.left,curSum);
}
if(!br) {
dfs(g,l,root.right,curSum);
}
//记得要回溯
l.removeLast();
}
}
下面是另一种写法:这个写法有点不安全,每次递归不检查 root是否为空,为了快使用数组
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int sum;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
LinkedList<List<Integer>> g = new LinkedList();
if(root==null)
return g;
this.sum = sum;
ArrayList<Integer> l = new ArrayList();
dfs(g,l,root,0);
return g;
}
private void dfs(List<List<Integer>> g,ArrayList<Integer>l,TreeNode root,int curSum) {
boolean bl = root.left==null;
boolean br = root.right == null;
curSum += root.val;
l.add(root.val);
if(bl&&br) {
if(curSum == this.sum) {
List<Integer> ans = new ArrayList(l);
g.add(ans);
//记得要回溯
l.remove(l.size()-1);
return;
}
}
if(!bl) {
dfs(g,l,root.left,curSum);
}
if(!br) {
dfs(g,l,root.right,curSum);
}
//记得要回溯
l.remove(l.size()-1);
}
}