categories: [Blog,Algorithm]


112. 路径总和

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

示例 1:
112. 路径总和 - 图1
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true

广度优先

  1. public boolean hasPathSum(TreeNode root, int sum) {
  2. if (root == null) {
  3. return false;
  4. }
  5. Queue<TreeNode> queNode = new LinkedList<TreeNode>();
  6. Queue<Integer> queVal = new LinkedList<Integer>();
  7. queNode.offer(root);
  8. queVal.offer(root.val);
  9. while (!queNode.isEmpty()) {
  10. TreeNode now = queNode.poll();
  11. int temp = queVal.poll();
  12. if (now.left == null && now.right == null) {
  13. if (temp == sum) {
  14. return true;
  15. }
  16. continue;
  17. }
  18. if (now.left != null) {
  19. queNode.offer(now.left);
  20. queVal.offer(now.left.val + temp);
  21. }
  22. if (now.right != null) {
  23. queNode.offer(now.right);
  24. queVal.offer(now.right.val + temp);
  25. }
  26. }
  27. return false;
  28. }
  29. 作者:LeetCode-Solution
  30. 链接:https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/

递归

  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 sum) {
  18. if (root == null) {
  19. return false;
  20. }
  21. if (root.left == null && root.right == null) {
  22. return sum == root.val;
  23. }
  24. return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
  25. }
  26. // 作者:LeetCode-Solution
  27. // 链接:https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/
  28. }