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

    题目描述

    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
    代码:
    1. // 二叉树中和为某一值的路径  
    2.     /** 
    3.      * 题目描述 
    4.      * 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 
    5.      */  
    6.   
    7.     ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();  
    8.     ArrayList<Integer> current = new ArrayList<>();  
    9.   
    10.     public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {  
    11.         if (root == null) {  
    12.             return arrayList;  
    13.         }  
    14.   
    15.         current.add(root.val);  
    16.   
    17.         if (root.left == null && root.right == null) {  
    18.             if (!current.isEmpty()) {  
    19.                 int sum = 0;  
    20.                 for (int i : current) {  
    21.                     sum += i;  
    22.                 }  
    23.                 if (sum == target) {  
    24.                     ArrayList<Integer> list = new ArrayList<>(current);  
    25.                     arrayList.add(list);  
    26.                 }  
    27.             }  
    28.         }  
    29.         FindPath(root.left, target);  
    30.         FindPath(root.right, target);  
    31.         current.remove(current.size() - 1);  
    32.   
    33.         return arrayList;  
    34.     }  

    第二种:

    链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
    来源:牛客网

    public class Solution {
        private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
        private ArrayList<Integer> list = new ArrayList<Integer>();
        public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
            if(root == null) return listAll;
            list.add(root.val);
            target -= root.val;
            if(target == 0 && root.left == null && root.right == null)
                listAll.add(new ArrayList<Integer>(list));
            FindPath(root.left, target);
            FindPath(root.right, target);
            list.remove(list.size()-1);
            return listAll;
        }
    }
  • 相关阅读:
    免费第三方API平台整合
    接口使用数据库缓存考虑的不周到之处
    找了两个小时的错误,net.sf.json.JSONException: JSON keys cannot be null.
    jsp动态页面访问报错:HTTP Status 500
    JAVA中json转换为集合(对象)之间的相互转换
    听头条
    使用DataOutputStream输出流的read方法出现读取字节不一致解决办法,本地和测试环境不一致
    ibatis中的xml配置文件
    poj 1325 Machine Schedule 题解
    poj 1469 COURSES 题解
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7426354.html
Copyright © 2011-2022 走看看