437. 路径总和 III

原题链接:

437. 路径总和 III
https://leetcode.cn/problems/path-sum-iii/

完成情况:

在这里插入图片描述

解题思路:

用一个队列最整个树进行BFS遍历,然后计算累加和,集合。。。

  if(Sum > 2147483647 || Sum<-2147483648){
                return;
            }

注意一下,数值溢出的问题,会超出,导致有一个无法通过。

参考代码:

package 西湖算法题解;

import java.util.ArrayDeque;
import java.util.Queue;

public class __437路径总和III__方法二 {
	public static void main(String[] args) {

	}

	  public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }

	  /**
		   *
		   * 二叉树的节点个数的范围是 [0,1000]
		   * -109 <= Node.val <= 109
		   * -1000 <= targetSum <= 1000
		   *
		   * @param root
		   * @param targetSum
		   * @return
	   */

	  int targetSum,count= 0;

	  public int pathSum(TreeNode root, int targetSum){
			/*
			没啥技巧,就是一个BFS,然后用一个res记录每次累加的结果,用一个count记录出现你要的结果的出现次数
			 */
		  if (root == null) {
			  return 0;
		  }
		  this.targetSum = targetSum;
		  Queue<TreeNode> queue = new ArrayDeque<>();
		  queue.add(root);
		  while (queue.isEmpty()){
			  TreeNode node = queue.remove();
			  BFStoSum(node,0);
			  if (node.left != null){
				  queue.add(node.left);
			  }
			  if (node.right != null){
				  queue.add(node.right);
			  }
		  }
		  return count;
	  }

		  private void BFStoSum(TreeNode root, long Sum) {
			if (root == null){
				return ;
			}
			int val = root.val;

			Sum += val;
			if (Sum == targetSum){
				count++;
			}
			//等于也得继续调它的左右节点进行累加
			BFStoSum(root.left,Sum);
			BFStoSum(root.right,Sum);
		  }
	  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值