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

今天和大家聊的问题叫做 路径总和 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 的 路径 的数目。路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

示例

​LeetCode刷题实战437:路径总和 III_二叉树


解题


路径的开头可以不是根节点,结束也可以不是叶子节点,是不是有点复杂?

如果问题是这样:找出以根节点为开始,任意节点可作为结束,且路径上的节点和为 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;
}
}


​LeetCode刷题实战437:路径总和 III_二叉树_02