zoukankan      html  css  js  c++  java
  • 剑指offer-二叉树中和为某一值的路径

    题目描述

    输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
     
    使用dfs
     1 public class Solution {//dfs 树 my
     2     ArrayList<ArrayList<Integer>> re ;
     3     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
     4         re = new ArrayList<>();
     5         if(root!=null){
     6             dfs(root,new ArrayList<Integer>(),target,0);
     7         }
     8         return re;
     9     }
    10     public void dfs(TreeNode root ,ArrayList<Integer> list,int target,int sum){
    11         if(root.left==null&&root.right==null){
    12             if((sum+root.val)==target){
    13                 //添加路径
    14                 ArrayList l =new ArrayList<Integer>(list);
    15                 l.add(root.val);
    16                 re.add(l);
    17                 return;
    18             }
    19             return;
    20         }
    21         sum +=root.val;
    22         list.add(root.val);
    23         if(root.left!=null){
    24             dfs(root.left,list,target,sum);
    25         }
    26         if(root.right!=null){
    27             dfs(root.right,list,target,sum);
    28         }
    29         sum-=root.val;
    30         list.remove(list.size()-1);
    31         return ;
    32     }
    33 }

    其中和可简化为一个参数,如下

     1 public class Solution {
     2     ArrayList<ArrayList<Integer>> re ;
     3     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
     4         re = new ArrayList<>();
     5         if(root!=null){
     6             dfs(root,new ArrayList<Integer>(),target);
     7         }
     8         return re;
     9     }
    10     public void dfs(TreeNode root ,ArrayList<Integer> list,int target){
    11         if(root.left==null&&root.right==null){
    12             if(root.val==target){
    13                 //添加路径
    14                 ArrayList l =new ArrayList<Integer>(list);
    15                 l.add(root.val);
    16                 re.add(l);
    17                 return;
    18             }
    19             return;
    20         }
    21         list.add(root.val);
    22         if(root.left!=null){
    23             dfs(root.left,list,target-root.val);
    24         }
    25         if(root.right!=null){
    26             dfs(root.right,list,target-root.val);
    27         }
    28         list.remove(list.size()-1);
    29         return ;
    30     }
    31 }
  • 相关阅读:
    医学影像
    阿里云九卿 大数据产业化
    陈海青 阿里
    店铺高频问题主动生成知识点机器 大脑+人脑 知识库
    数据总线和流计算在城市大脑中的应用
    无推荐不APP
    ww
    业务架构
    jd算法大赛 一个user_id只需映射到一个sku_id, 但是一个sku_id能否映射到多个user_id
    短URL DH 密钥交换算法
  • 原文地址:https://www.cnblogs.com/zhacai/p/10695818.html
Copyright © 2011-2022 走看看