Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree andsum =
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
代码 1
import java.util.ArrayList; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> arr=new ArrayList<Integer>(); public boolean hasPathSum(TreeNode root, int sum) { if(root==null)return false; isPath(root,0,sum); if(result.isEmpty())return false; else return true; } private void isPath(TreeNode root, int sum, int target) { if(root==null)return; else{ sum+=root.val; arr.add(root.val); if(root.left==null&&root.right==null&&sum==target){ result.add(new ArrayList<Integer>(arr)); } isPath(root.left, sum, target); isPath(root.right, sum, target); arr.remove(arr.size()-1); sum-=root.val; } } }
代码二:
import java.util.ArrayList; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public boolean hasPathSum(TreeNode root, int sum) { return hasPathSumHelper(root, sum); } private boolean hasPathSumHelper(TreeNode root, int sum) { // TODO Auto-generated method stub if(root==null)return false; if(root.left==null&&root.right==null&&sum==root.val)return true; return hasPathSumHelper(root.left, sum-root.val)||hasPathSumHelper(root.right, sum-root.val); } }
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】园子的不务正业:向创业开发者推荐「楼盘」- 杭州云谷中心
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】天翼云爆款云主机2核2G限时秒杀,28.8元/年起!立即抢购
· Ribbon LoadBalancer: 开源的客户端式负载均衡框架
· EF Core:再谈普通实体关系与 Owned 关系的区别
· C++20新增属性[[no_unique_address]]详解
· 线上频繁FullGC?竟是Log4j2的这个“特性”坑了我
· 聊一聊 .NET 中的 CancellationTokenSource
· 刚刚 Java 25 炸裂发布!让 Java 再次伟大
· 一款基于 .NET 开源美观、功能丰富的串口调试工具
· .NET 10 是微软 AI 战略的技术承重墙
· Runtime Async - 步入高性能异步时代
· AI 开发者工具 TOP 榜:9 大分类 + 20种工具