路径总和

题目描述:给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。

叶子节点 是指没有子节点的节点。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:递归

首先,如果root为null,直接返回false。

否则,调用递归方法hasPathSum(TreeNode root, int targetSum, int curSum),root为当前节点,targetSum为目标和,curSum当前路径上的累加和,递归过程如下:

  • 如果root为null,直接返回;
  • 否则,curSum累加当前节点的值;
  • 然后判断如果root的左子树或者右子树有一边为null,则调用递归方法,参数为不为null的子树和curSum,然后返回;
  • 如果root的左子树和右子树都不为null,则左右子树都要调用递归方法。

过程中当到达子节点时需要判断当前路径的和curSum和targetSum是否相等,如果相等,则将result更新为true,最后返回result。

说明:该题的解法过程和 LeetCode-111-二叉树的最小深度 完全一样。

  1. public class LeetCode_112 {
  2. public static boolean result = false;
  3. public static boolean hasPathSum(TreeNode root, int targetSum) {
  4. if (root == null) {
  5. return false;
  6. }
  7. hasPathSum(root, targetSum, 0);
  8. return result;
  9. }
  10. public static void hasPathSum(TreeNode root, int targetSum, int curSum) {
  11. if (root == null) {
  12. return;
  13. }
  14. curSum += root.val;
  15. if (root.left == null && root.right == null) {
  16. if (curSum == targetSum) {
  17. result = true;
  18. }
  19. return;
  20. }
  21. if (root.left == null && root.right != null) {
  22. hasPathSum(root.right, targetSum, curSum);
  23. return;
  24. }
  25. if (root.left != null && root.right == null) {
  26. hasPathSum(root.left, targetSum, curSum);
  27. return;
  28. }
  29. hasPathSum(root.left, targetSum, curSum);
  30. hasPathSum(root.right, targetSum, curSum);
  31. }
  32. public static void main(String[] args) {
  33. TreeNode root = new TreeNode(1);
  34. root.left = new TreeNode(2);
  35. root.right = new TreeNode(3);
  36. System.out.println(hasPathSum(root, 5));
  37. System.out.println(hasPathSum(root, 4));
  38. }
  39. }

【每日寄语】 收集每一个快乐的瞬间,用它来回击每一个糟糕的日子。