• 剑#指 Offer 34. 二叉树中和为某一值的路径


    剑指 Offer 34. 二叉树中和为某一值的路径

    List不能只增加接口 必须实现类Arraylist or linkedlist

    给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

    叶子节点 是指没有子节点的节点。

    示例 1:

    输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
    输出:[[5,4,11,2],[5,8,4,5]]
    示例 2:

    输入:root = [1,2,3], targetSum = 5
    输出:[]
    示例 3:

    输入:root = [1,2], targetSum = 0
    输出:[]

    提示:

    树中节点总数在范围 [0, 5000] 内
    -1000 <= Node.val <= 1000
    -1000 <= targetSum <= 1000
    注意:本题与主站 113 题相同:https://leetcode-cn.com/problems/path-sum-ii/

    通过次数174,933提交次数299,751

     class Solution {
            
            List<List<Integer>> res =new ArrayList<>();
    
            public List<List<Integer>> pathSum(TreeNode root, int target) {
                 List<Integer> list = new ArrayList<>();
                path(0,root,target,list);
    
                return res;
            }
    
            public void path(int sum ,TreeNode root, int target,List<Integer> list)
            {
    
                if(root==null) 
                {
                  return;
                }
                sum+=root.val;  //5+ 4+11+2
                        System.out.println(sum);
                System.out.println(root.val);
                list.add(root.val);
              
                if(sum==target&&root.left==null&&root.right==null)
                {        System.out.println("root is null ");
                    res.add(new LinkedList<Integer>(list));//加接口没有答案
                }
              
                    path(sum,root.left,target,list);
            
              
            
                    path(sum,root.right,target,list);
    
    
                    list.remove(list.size()-1);   
                  //把不符合题意的叶子节点直接移除。
           
            }
        }
    
  • 相关阅读:
    PHP实现微信退款的分析与源码实现
    thinkphp对180万数据批量更新支持事务回滚
    在线工具
    php连接redis
    Redis PHP连接操作
    阿里大于短信接口整合TP5
    Unity3d中如何查找一个脚本被挂在那些预设上面?
    泰课在线夜猫的贪食蛇
    EasyTouch5ForSiki学院
    unity游戏热更新
  • 原文地址:https://www.cnblogs.com/shenxiaodou/p/16027957.html
Copyright © 2020-2023  润新知