• 剑指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;
        }
    }
  • 相关阅读:
    两年来的读书小总结(20112013)
    给无边框窗体添加任务栏右键菜单
    使用 yum 命令安装本地安装QQ
    删除非空目录
    gcc安装
    WIN32::OLE操作之excel
    [题解] 组合数学13题
    [算法] 高斯消元及其应用
    [算法] Lucas 定理
    [算法] 最小费用最大流
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7426354.html
Copyright © 2020-2023  润新知