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;
        }
    }
  • 相关阅读:
    Leetcode 1489找到最小生成树李关键边和伪关键边
    Leetcode 113 路径总和 II
    hdu 1223 还是畅通工程
    hdu 1087 Super Jumping! Jumping! Jumping!
    hdu 1008 Elevator
    hdu 1037 Keep on Truckin'
    湖工oj 1241 畅通工程
    湖工oj 1162 大武汉局域网
    hdu 2057 A + B Again
    poj 2236 Wireless Network
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7426354.html
Copyright © 2011-2022 走看看