当前位置:网站首页>Leetcode 112: path sum
Leetcode 112: path sum
2022-07-29 01:49:00 【Swarford】
subject :
Ideas :dfs
The idea is similar to Change for , Every time you recurse down , Add up the number you want sum Subtract the current node root Of val, In this way, we can get the money we need to collect from the next layer , Until the leaf node sum Node equal val Return true !
The topic is about root node to leaf node ! So we have to traverse to the end , Use post order traversal ;
Single layer node : Determine whether it is currently a leaf node , Yes, judge sum and val Whether it is equal or not ; If it's not a leaf node , Continue to recursive ;
base case: If root==null ,return false;
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// You must go to the leaf node !
// You must traverse to the end ! dfs
// Traversing to the leaf node is not equal to sum, Then return to false;
if(root==null){
return false;
}
// Catch the result , to flash back
boolean left=hasPathSum(root.left,sum-root.val);
boolean right=hasPathSum(root.right,sum-root.val);
// Current node :
// To the left and right null Is the leaf node !
if(root.left==null && root.right==null){
// Traverse to the end , here root value =sum To return to true !
return root.val==sum;
}
return left || right;
}
}
边栏推荐
猜你喜欢

What is the ISO assessment? How to do the waiting insurance scheme

【公开课预告】:快手GPU/FPGA/ASIC异构平台的应用探索

10 major network security incidents in the past 10 years

SiC Power Semiconductor Industry Summit Forum successfully held

Focus on differentiated product design, intelligent technology efficiency improvement and literacy education around new citizen Finance

知道创宇上榜CCSIP 2022全景图多个领域

Where will Jinan win in hosting the first computing power conference?

MPEG音频编码三十年

动态内存与智能指针

Event express | Apache Doris Performance Optimization Practice Series live broadcast course is open at the beginning. You are cordially invited to participate!
随机推荐
Understand various paths
Use of resttemplate and Eureka
[hcip] OSPF experiment under mGRE environment, including multi process bidirectional republication and OSPF special area
科研环境对人的影响是很大的
Read the recent trends of okaleido tiger and tap the value and potential behind it
matplotlib中文问题
Ruiji takeout project actual battle day01
Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security
body中基本标签
StoneDB 为何敢称业界唯一开源的 MySQL 原生 HTAP 数据库?
Autoware reports an error: can't generate global path for start solution
TypeError: can only concatenate str (not “int“) to str
数据平台数据接入实践
golang run时报undefined错误【已解决】
JS event introduction
【HCIP】重发布及路由策略的实验
九天后我们一起,聚焦音视频、探秘技术新发展
Moonbeam上的多链用例解析——Derek在Polkadot Decoded 2022的演讲文字回顾
CSDN modify column name
Reinforcement learning (I): Q-learning, with source code interpretation