二叉树中和为目标值的路径 (二叉树中和为目标值的路径)

 

思路:

// @Title: 二叉树中和为目标值的路径 (二叉树中和为目标值的路径)
// @Author: qisiii
// @Date: 2022-02-21 13:57:26
// @Runtime: 1 ms
// @Memory: 41.6 MB
// @comment: 
// @flag: 
/**
 * 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 {
    public static List<List<Integer>> pathSum(TreeNode root, int target) {
        if (root == null) {
            return new ArrayList();
        }
        List<List<Integer>> result = new ArrayList<>();
        if (root.left==null&&root.right==null){
            if(target==root.val){
                result.add(new ArrayList<>());
            }else {
                return new ArrayList();
            }
        }
            List<List<Integer>> lists = pathSum(root.left, target - root.val);
            if (lists!=null&&!lists.isEmpty()) {
                result.addAll(lists);
            }

            List<List<Integer>> lists1 = pathSum(root.right, target - root.val);
            if (lists1!=null&&!lists1.isEmpty()){
                result.addAll(lists1);
            }

        for (List<Integer> integers : result) {
            integers.add(0, root.val);
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18