题解 | #回文数字#
二叉树根节点到叶子节点和为指定值的路径
https://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a?tpId=188&&tqId=38567&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @param sum int整型 * @return int整型ArrayList<ArrayList<>> */ static ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();//存放结果 static int sumNum; static ArrayList<Integer> path = new ArrayList<Integer>();//存放路径 public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) { sumNum = sum; findPath(root,0); // write code here return res; } //定义一个集合 static void findPath(TreeNode root, int temps){ if(root == null){ return; } path.add(root.val); temps = temps + root.val; if(temps == sumNum && root.left == null && root.right == null){ res.add(new ArrayList<Integer>(path));//复制一个 //不然还是不断改变 path.remove(path.size()-1); return; } if(root.left != null){ findPath(root.left,temps); } if(root.right != null){ findPath(root.right,temps); } path.remove(path.size()-1); } }