zl程序教程

您现在的位置是:首页 >  其他

当前栏目

​LeetCode刷题实战437:路径总和 III

2023-03-14 22:50:56 时间

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

今天和大家聊的问题叫做 路径总和 III,我们先来看题面:

https://leetcode-cn.com/problems/path-sum-iii/

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum 的 路径 的数目。

路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

示例

解题

https://www.shuzhiduo.com/A/D854DXRp5E/

路径的开头可以不是根节点,结束也可以不是叶子节点,是不是有点复杂? 如果问题是这样:找出以根节点为开始,任意节点可作为结束,且路径上的节点和为 sum 的路径的个数; 是不是前序遍历一遍二叉树就可以得到所有这样的路径?是的; 如果这个问题解决了,那么原问题可以分解成多个这个问题; 是不是和数线段是同一个问题,只不过线段变成了二叉树; 在解决了以根节点开始的所有路径后,就要找以根节点的左孩子和右孩子开始的所有路径,三个节点构成了一个递归结构;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   /**
     * 求以 root 为根的二叉树,所有和为 sum 的路径;
     * 路径的开头不一定是 root,结尾也不一定是叶子节点;
     * @param root
     * @param sum
     * @return
     */
    public int pathSum(TreeNode root, int sum) {
 
        if (root == null) {
            return 0;
        }
 
        return paths(root, sum)
                + pathSum(root.left, sum)
                + pathSum(root.right, sum);
    }
 
    private int paths(TreeNode root, int sum) {
 
        if (root == null) {
            return 0;
        }
 
        int res = 0;
        if (root.val == sum) {
            res += 1;
        }
 
        res += paths(root.left, sum - root.val);
        res += paths(root.right, sum - root.val);
 
        return res;
    }
}

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

上期推文:

LeetCode1-420题汇总,希望对你有点帮助!

LeetCode刷题实战421:数组中两个数的最大异或值

LeetCode刷题实战422:有效的单词方块

LeetCode刷题实战423:从英文中重建数字

LeetCode刷题实战424:替换后的最长重复字符

LeetCode刷题实战425:单词方块

LeetCode刷题实战426:将二叉搜索树转化为排序的双向链表

LeetCode刷题实战427:建立四叉树

LeetCode刷题实战428:序列化和反序列化 N 叉树

LeetCode刷题实战429:N 叉树的层序遍历

LeetCode刷题实战430:扁平化多级双向链表

LeetCode刷题实战431:将 N 叉树编码为二叉树

LeetCode刷题实战432:全 O(1) 的数据结构

LeetCode刷题实战433:最小基因变化

LeetCode刷题实战434:字符串中的单词数

LeetCode刷题实战435:无重叠区间

LeetCode刷题实战436:寻找右区间