当前位置:网站首页>【JZOF】82二叉树中和为某一值的路径(一)
【JZOF】82二叉树中和为某一值的路径(一)
2022-08-09 22:11:00 【叹了口丶气】
题目描述:
给定一个二叉树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;
// 内部类,将部分路径和与当前节点相关联
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;
}
// 使用队列在遍历过程中存储节点
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;
}
}
边栏推荐
- 使用股票量化交易接口需要具备怎么样的心态
- 【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
- 高手这样看现货白银走势图
- 继承关系下构造方法的访问特点
- 联盟链技术应用的难点
- Linux 配置MySQL
- APS系统能消除造成生产和运输延迟的瓶颈
- 深度学习100例 —— 循环神经网络(RNN)实现股票预测
- Users should clearly know that quantitative trading is not a simple procedure
- VR全景拍摄如何拍摄?如何使用拍摄器材?
猜你喜欢
随机推荐
HBuilder X 不能运行到内置终端
Leetcode 98. 验证二叉搜索树
Pytorch分布式训练/多卡训练DDP——模型初始化(torch.distribute 与 DDP的区别)
后台管理实现导入导出
JS--popstate事件--使用/教程/实例
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
matplotlib散点图颜色分组图例
6款跨境电商常用工具汇总
力扣:377. 组合总和 Ⅳ
SRv6性能测量
探索TiDB Lightning源码来解决发现的bug
国内十大活跃报表 BI 产品深度对比及点评
带着昇腾去旅行:一日看尽金陵城里的AI胜景
DXF笔记:文字对齐的研究
力扣:474.一和零
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
信息系统项目管理师---第十一章项目风险管理历年考题
String类常用方法
继承关系下构造方法的访问特点
Users should clearly know that quantitative trading is not a simple procedure