Sword Finger Offer Interview Questions 34. The path where the sum is a certain value in the binary tree (dfs)

Topic
Insert picture description here
There are many pits note the leaf node that is come to the bottom of the binary tree
began to write linkedlist time 2ms
for a 1ms arraylist on a
very puzzled hope that understanding back to elaborate

class Solution {
    
    
    List<List<Integer>> res;
    int target;
    List<Integer> list;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
    
    
        this.target = target;
        res = new ArrayList<>();
        if (root == null) return res;
        list = new ArrayList<>();
        list.add(root.val);
        dfs(list,root,1,root.val);
        return res;
    }
    private void dfs(List list, TreeNode node, int step,int sum){
    
    
        if (sum == target && node.left == null && node.right == null){
    
    
            res.add(new ArrayList<>(list));
            return;
        }
        if (node.left != null){
    
    
            list.add(node.left.val);
            dfs(list,node.left,step+1,sum+node.left.val);
            list.remove(step);
        }
        if (node.right != null){
    
    
            list.add(node.right.val);
            dfs(list,node.right,step+1,sum+node.right.val);
            list.remove(step);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_43434328/article/details/115305272