当前位置:网站首页>[JZOF] 82 binary tree with a path of a certain value (1)
[JZOF] 82 binary tree with a path of a certain value (1)
2022-08-10 00:32:00 【sigh】
题目描述:
给定一个二叉树root和一个值 sum ,判断是否有从根节点到叶子节点的节点值之和等于 sum 的路径.
1.该题路径定义为从树的根结点开始往下一直到叶子结点所经过的结点.
2.叶子节点是指没有子节点的节点.
3.路径只能从父节点到子节点,不能从子节点到父节点.
4.总节点数目为n.
一、递归遍历:
import java.util.*;
public class Solution {
public boolean hasPathSum (TreeNode root, int sum) {
// write code here
if (root == null ) {
return false;
}
if (sum == root.val && root.left == null && root.right == null) {
return true;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
二、层次遍历
import java.util.*;
/* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */
public class Solution {
/** * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */
class Pair{
TreeNode node = null;
int curSum = 0;
// 内部类,Associate a partial path sum with the current node
public Pair(TreeNode node,int curSum){
this.node = node;
this.curSum = curSum;
}
}
public boolean hasPathSum (TreeNode root, int sum) {
// 根节点为空,返回false
if (root == null){
return false;
}
// Use a queue to store nodes during traversal
Queue<Pair> nodeQueue= new LinkedList<>();
Pair pair = new Pair(root,root.val);
nodeQueue.add(pair);
Pair curPair = null;
// 层次遍历,根,左,右
while(!nodeQueue.isEmpty()){
curPair = nodeQueue.poll();
// 左节点非空
if (curPair.node.left != null){
nodeQueue.add(new Pair(
curPair.node.left,
curPair.curSum+curPair.
node.left.val));
}
// 右节点非空
if (curPair.node.right != null){
nodeQueue.add(new Pair(
curPair.node.right,
curPair.curSum+curPair.
node.right.val));
}
// 判断是否为叶子节点,是则与sum进行比较
if (curPair.node.left==null&&curPair.node.right==null){
if (sum == curPair.curSum){
return true;
}
}
}
return false;
}
}
边栏推荐
- 打包报错 AAPT: error: failed to read PNG signature: file does not start with PNG signature.
- Bi Sheng Compiler Optimization: Lazy Code Motion
- 【燃】是时候展现真正的实力了!一文看懂2022华为开发者大赛技术亮点
- Sqlserver限制账户在哪些ip下才可以访问数据库
- Mysql集群 ShardingSphere
- 高手这样看现货白银走势图
- Chapter 15 HMM模型
- daemon
- Controller层代码这么写,简洁又优雅!
- 【云原生】一文讲透Kubevela addon如何添加腾讯Crane
猜你喜欢
直播预告 | ICML 2022 11位一作学者在线分享神经网络,图学习等前沿研究
The 2022-8-9 sixth group of input and output streams
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
【TS技术课堂】时间序列预测
Install win7 virtual machine in Vmware and related simple knowledge
完全背包理论
数字与中文大写数字互转(5千万亿亿亿亿以上的数字也支持转换)
外包的水有多深?腾讯15k的外包测试岗能去吗?
如何正则匹配乱码?
一体化伺服电机在三轴钻孔机中的应用
随机推荐
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
mysql中的key是怎么用的,或者这个值有什么意义,如下图?
2022-8-9 第六组 输入输出流
Redis集群
Interfering with BGP routing---community attributes
华为云全流程护航《流浪方舟》破竹首发,打造口碑爆款
干涉BGP的选路---社团属性
【云原生】一文讲透Kubevela addon如何添加腾讯Crane
力扣:518. 零钱兑换 II
Qt message mechanism and events
浅析量股票化交易的发展现状
Janus官方DEMO介绍
tiup cluster upgrade
为什么刀具数据库无法打开?
UNI-APP_监听页面滚动h5监听页面滚动
CGLIB源码易懂解析
力扣:474.一和零
金仓数据库 KingbaseGIS 使用手册(6.5. 几何对象编辑函数)
干货!迈向鲁棒的测试时间适应
【面试高频题】可逐步优化的链表高频题