题解 | #二叉树根节点到叶子节点和为指定值的路径#
二叉树根节点到叶子节点和为指定值的路径
https://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a
记录:
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<>> */ public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) { // write code here ArrayList<ArrayList<Integer>> out = new ArrayList<>(); if (root == null) { return out; } else { Stack<TreeNode> st = new Stack<>(); Stack<ArrayList<Integer>> stp = new Stack<>(); ArrayList<Integer> path = new ArrayList<>(); path.add(root.val); st.add(root); stp.add(path); while (!st.isEmpty()) { TreeNode temp = st.pop(); ArrayList<Integer> tempp = stp.pop(); if (temp.left == null && temp.right == null) { int sumtemp = tempp.stream().mapToInt(n -> n).sum(); if (sumtemp == sum) { out.add(tempp); } } if (temp.right != null) { st.push(temp.right); tempp.add(temp.right.val); stp.push(new ArrayList<>(tempp)); tempp.remove(tempp.size() - 1); } if (temp.left != null) { st.push(temp.left); tempp.add(temp.left.val); stp.push(new ArrayList<>(tempp)); tempp.remove(tempp.size() - 1); } } return out; } } }