树的回溯
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
dfs(root, "", res);
return res;
}
public void dfs(TreeNode root, String path, List<String> res){
if(root == null){
return;
}
if(root.left == null && root.right == null){
path = path + root.val;
res.add(path);
}else{
path = path + root.val + "->";
}
dfs(root.left, path, res);
dfs(root.right, path, res);
}
}
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
int sum = 0;
dfs(root, targetSum, sum, res, path);
return res;
}
public void dfs(TreeNode root, int targetSum, int sum, List<List<Integer>> res, Deque<Integer> path){
if(root == null){
return;
}
sum = sum + root.val;
path.addLast(root.val);
if(sum == targetSum && root.left == null && root.right == null){
res.add(new ArrayList<>(path));
}
dfs(root.left, targetSum, sum, res, path);
dfs(root.right, targetSum, sum, res, path);
path.removeLast();
}
}
注意: 树的回溯不要在res.add后return;否则在下一次从根节点开始选择时无法remove所有节点。而且基本是前序遍历。