当前位置:网站首页>Sword finger offer 34 A path with a value in a binary tree

Sword finger offer 34 A path with a value in a binary tree

2022-06-21 07:29:00 South wind knows easy***

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
    
    List<List<Integer>> res=new ArrayList<>();
    LinkedList<Integer> path=new LinkedList<>();
    int target;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
    
        this.target=target;
        recur(root);
        return res;
    }

    public void recur(TreeNode root){
    
        if(root==null) return;
        path.add(root.val);
        if(root.left==null&&root.right==null){
    
            int sum=0;
            for(int item:path){
    
                sum+=item;
            }
            if(sum==target) res.add(new ArrayList(path)); Be careful !!!!
        }

        if(root.left!=null){
    
            recur(root.left);
        }
        if(root.right!=null){
    
            recur(root.right);
        }
        path.removeLast();
    }
}
原网站

版权声明
本文为[South wind knows easy***]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221515179613.html