二叉树的路径问题dfs:
力扣257,404,112路径总和,437路径总和
1.二叉树的所有路径(带回溯)
public List<String> binaryTreePaths(TreeNode root) {
if(root==null){
return res;
}
backTrack(root);
return res;
}
private void backTrack(TreeNode root){
path.add(root.val);
if(root.left==null&&root.right==null){
for(int i=0;i<path.size();i++){
sb.append(path.get(i)).append("->");
}
res.add(sb.toString().substring(0,sb.length()-2));
sb=new StringBuilder();
return;
}
if(root.left!=null){
backTrack(root.left);
path.remove(path.size()-1);
}
if(root.right!=null){
backTrack(root.right);
path.remove(path.size()-1);
}
2.左叶子之和
if(root==null){
return res;
}
findSum(root);
return res;
}
private int findSum(TreeNode root){
if(root==null){
return 0;
}
int leftSum = findSum(root.left);
int rightSum = findSum(root.right);
if(root.left!=null&&root.left.left==null&&root.left.right==null){
res+=root.left.val;
}
return res;
3.路径总和
if(root==null){
return res;
}
backTrack(root,targetSum);
return res;
}
private void backTrack(TreeNode root,int targetSum){
sum+=root.val;
if(root.left==null&&root.right==null){
if(sum==targetSum){
res=true;
return;
}else{
return;
}
}
if(root.left!=null) {
backTrack(root.left, targetSum);
sum-=root.left.val;
}
if(root.right!=null) {
backTrack(root.right, targetSum);
sum-=root.right.val;
}
}
4.路径总和(前缀和)
if(root==null){
return res;
}
Map<Integer,Integer>map=new HashMap<>();
map.put(0,1);
findPathSum(root,targetSum,map,0);
return res;
}
private void findPathSum(TreeNode root,int targetSum,Map<Integer,Integer>map,int sum){
if(root==null){
return;
}
sum+=root.val;
if(map.containsKey(sum-targetSum)){
res+=map.get(sum-targetSum);
}
map.put(sum,map.getOrDefault(sum,0)+1);
findPathSum(root.left,targetSum,map,sum);
findPathSum(root.right,targetSum,map,sum);
map.put(sum,map.getOrDefault(sum,0)-1);