标签:pat class import pre integer arraylist res 程序 amp
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
find(root.left,target,res,new ArrayList<>(path)); find(root.right,target,res,new ArrayList<>(path));
采用new ArrayList<>(path)是保证遍历完左节点后,将path变为之前的状态再去遍历右节点。
import java.util.ArrayList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList <ArrayList<Integer>> res = new ArrayList<>(); if (root == null){ return res; } ArrayList<Integer> path = new ArrayList<>(); find(root,target,res,path); return res; } public void find (TreeNode root,int target,ArrayList<ArrayList<Integer>> res,ArrayList<Integer> path){ if (root == null){ return; } target = target - root.val; path.add(root.val); if (target == 0 && root.left == null && root.right == null){ res.add(path); return; } find(root.left,target,res,new ArrayList<>(path)); find(root.right,target,res,new ArrayList<>(path)); } }
标签:pat class import pre integer arraylist res 程序 amp
原文地址:https://www.cnblogs.com/xxc-Blog/p/12530714.html