题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
import java.util.ArrayList; import java.util.LinkedList; import java.util.stream.Collectors; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */ public boolean hasPathSum (TreeNode root, int sum) { ArrayList<ArrayList<Integer>> results = new ArrayList<>(); LinkedList<Integer> queue = new LinkedList<>(); int sumAll = 0; if (root != null) { addDatas(root, sum, results, queue, sumAll); } return results.size() > 0; } private void addDatas(TreeNode root, int expectNumber, ArrayList<ArrayList<Integer>> results, LinkedList<Integer> queue, int sumAll) { if (root != null) { sumAll += root.val; queue.add(root.val); if (sumAll == expectNumber && root.left == null && root.right == null) { addResult(results, queue); } else { addDatas(root.left, expectNumber, results, queue, sumAll); addDatas(root.right, expectNumber, results, queue, sumAll); } queue.pollLast(); sumAll -= root.val; } } private void addResult(ArrayList<ArrayList<Integer>> results, LinkedList<Integer> queue) { // 循环队列中的元素 ArrayList<Integer> result = (ArrayList)queue.stream().collect( Collectors.toList()); results.add(result); } }
解题思想:队列+递归+回朔
#算法##算法笔记#