LeetCode刷题实战112:路径总和
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 路径总和,我们先来看题面:
https://leetcode-cn.com/problems/path-sum/
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.
Note: A leaf is a node with no children.
题意
解题
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.val == sum && root.left == null && root.right == null) {
return true;
}
if (root.left != null) {
if (hasPathSum(root.left, sum - root.val)) {
return true;
}
}
if (root.right != null) {
return hasPathSum(root.right, sum - root.val);
}
return false;
}
}
上期推文: