​LeetCode刷题实战112:路径总和

程序IT圈

共 1573字,需浏览 4分钟

 ·

2020-12-06 20:46

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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.

题意


给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

样例

解题

https://www.yuque.com/zhoujx/study/lc112

现在看到这种题,就考虑了递归,从根节点开始递归遍历,sum递减计算,如果遍历到左、右节点为null且节点的值等于传过来的就表示存在这样的路径。将思路写成代码,因为return语句的原因,所以在第一次递归的时候用if语句包了起来。

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;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。


上期推文:


LeetCode1-100题汇总,希望对你有点帮助!
LeetCode刷题实战101:对称二叉树
LeetCode刷题实战102:二叉树的层序遍历
LeetCode刷题实战103:二叉树的锯齿形层次遍历
LeetCode刷题实战104:二叉树的最大深度
LeetCode刷题实战105:从前序与中序遍历序列构造二叉树
LeetCode刷题实战106:从中序与后序遍历序列构造二叉树
LeetCode刷题实战107:二叉树的层次遍历 II
LeetCode刷题实战108:将有序数组转换为二叉搜索树
LeetCode刷题实战109:有序链表转换二叉搜索树
LeetCode刷题实战110:平衡二叉树
LeetCode刷题实战111:二叉树的最小深度

浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报