当前位置:网站首页>【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;
}
}
边栏推荐
猜你喜欢
随机推荐
JS--hashchange事件--使用/教程
数字与中文大写数字互转(5千万亿亿亿亿以上的数字也支持转换)
请讲一讲JS中的 for...in 与 for...of (上)
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
如何知道电脑开机记录?
Redis集群
CGLIB源码易懂解析
【技术分享】SLA(服务等级协议)原理与配置
【燃】是时候展现真正的实力了!一文看懂2022华为开发者大赛技术亮点
月薪5K的运维小白如何成为月薪5W的高级架构师?
How to insist to use procedural system?
力扣:279.完全平方数
信息系统项目管理师---第十一章项目风险管理历年考题
2022/8/9 考试总结
leetcode:321. 拼接最大数
Janus Official DEMO Introduction
Mysql集群 ShardingSphere
2022-08-09 mysql/stonedb-子查询性能提升-概论
Leetcode 530. 二叉搜索树的最小绝对差
上海一科技公司刷单被罚22万,揭露网络刷单灰色产业链









