题目

类型:DFS

难度:中等

路径总和II - 图1

解题思路

采用深度优先搜索的方式,枚举每一条从根节点到叶子节点的路径。

当遍历到叶子节点,且此时路径和恰为目标和时,就找到了一条满足条件的路径。

代码

  1. package depthFirstSearch;
  2. import common.TreeNode;
  3. import java.util.Deque;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. public class PathSumII {
  7. List<List<Integer>> ret = new LinkedList<List<Integer>>();
  8. Deque<Integer> path = new LinkedList<Integer>();
  9. public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
  10. dfs(root, targetSum);
  11. return ret;
  12. }
  13. public void dfs(TreeNode root, int targetSum) {
  14. if (root == null) {
  15. return;
  16. }
  17. path.offerLast(root.val);
  18. targetSum -= root.val;
  19. if (root.left == null && root.right == null && targetSum == 0) {
  20. ret.add(new LinkedList<Integer>(path));
  21. }
  22. dfs(root.left, targetSum);
  23. dfs(root.right, targetSum);
  24. path.pollLast();
  25. }
  26. }