112. 路径总和

image.png
image.png

回溯

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public boolean hasPathSum(TreeNode root, int targetSum) {
  18. if(root == null ) return false;
  19. return traversal(root,targetSum - root.val);
  20. }
  21. public boolean traversal(TreeNode cur, int count ) {
  22. // 遇到叶子节点,并且计数为0
  23. if( cur.left == null && cur.right == null && count == 0 ) return true;
  24. // 遇到叶子节点直接返回
  25. if( cur.left == null && cur.right == null ) return false;
  26. if(cur.left != null ) { // 左
  27. count -= cur.left.val; // 递归,处理节点;
  28. if(traversal(cur.left,count) ) return true;
  29. count += cur.left.val; // 回溯,撤销处理结果
  30. }
  31. if(cur.right != null ) {
  32. count -= cur.right.val; // 递归,处理节点;
  33. if(traversal(cur.right,count) ) return true;
  34. count += cur.right.val; // 回溯,撤销处理结果
  35. }
  36. return false;
  37. }
  38. }

回溯

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public boolean hasPathSum(TreeNode root, int targetSum) {
  18. if(root == null ) return false;
  19. // 叶子节点判断是否符合
  20. if(root.left == null && root.right == null ) return root.val == targetSum;
  21. // 求两侧分支的路径和
  22. return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val);
  23. }
  24. }