当前位置:网站首页>#yyds干货盘点# 解决剑指offer:二叉树中和为某一值的路径(三)
#yyds干货盘点# 解决剑指offer:二叉树中和为某一值的路径(三)
2022-06-27 15:33:00 【51CTO】
1.简述:
描述
给定一个二叉树root和一个整数值 sum ,求该树有多少路径的的节点值之和等于 sum 。1.该题路径定义不需要从根节点开始,也不需要在叶子节点结束,但是一定是从父亲节点往下到孩子节点2.总节点数目为n3.保证最后返回的路径个数在整形范围内(即路径个数小于231-1)
数据范围:
假如二叉树root为{1,2,3,4,5,4,3,#,#,-1},sum=6,那么总共如下所示,有3条路径符合要求
示例1
输入:
返回值:
说明:
示例2
输入:
返回值:
示例3
输入:
返回值:
2.代码实现:
import java.util.*;
public class Solution {
private int res = 0;
//dfs查询以某结点为根的路径数
private void dfs(TreeNode root, int sum){
if(root == null)
return;
//符合目标值
if(sum == root.val)
res++;
//进入子节点继续找
dfs(root.left, sum - root.val);
dfs(root.right, sum - root.val);
}
//dfs 以每个结点作为根查询路径
public int FindPath (TreeNode root, int sum) {
//为空则返回
if(root == null)
return res;
//查询以某结点为根的路径数
dfs(root, sum);
//以其子结点为新根
FindPath(root.left, sum);
FindPath(root.right, sum);
return res;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
边栏推荐
- 创建数据库并使用
- About fast exponentiation
- 机械硬盘和ssd固态硬盘的原理对比分析
- Condom giants' sales have fallen by 40% in the past two years. What are the reasons for the decline?
- Introduce you to ldbc SNB, a powerful tool for database performance and scenario testing
- [kotlin] the next day
- Design of digital video signal processor based on FPGA (with main code)
- Julia constructs diagonal matrix
- Introduction to TTCAN brick moving
- 关于TensorFlow使用GPU加速
猜你喜欢

Mobile terminal click penetration

【Pygame小遊戲】這款“吃掉一切”遊戲簡直奇葩了?通通都吃掉嘛?(附源碼免費領)

Weekly snapshot of substrate technology 20220411

分布式Session解决方案

What is the level 3 password complexity of ISO? How often is it replaced?

PSS:你距离NMS-free+提点只有两个卷积层 | 2021论文

About tensorflow using GPU acceleration

Keep valid digits; Keep n digits after the decimal point;

VS编译遇到的问题

A distribution fission activity is more than just a circle of friends!
随机推荐
Four characteristics of transactions
3.1 simple condition judgment
Mobile terminal click penetration
Difference between special invoice and ordinary invoice
Condom giants' sales have fallen by 40% in the past two years. What are the reasons for the decline?
What is the level 3 password complexity of ISO? How often is it replaced?
MySQL中符号@的作用
Mode setting of pulseaudio (21)
Design of CAN bus controller based on FPGA (with main codes)
Design of electronic calculator system based on FPGA (with code)
Piblup test report 1- pedigree based animal model
事务的四大特性
sql注入原理
字节跳动埋点数据流建设与治理实践
带你认识图数据库性能和场景测试利器LDBC SNB
事务的隔离级别详解
Practice of constructing ten billion relationship knowledge map based on Nebula graph
Pisa-Proxy 之 SQL 解析实践
正则匹配以什么开头、以什么结尾,以非什么开头,以非什么结尾
Weekly snapshot of substrate technology 20220411