112&113&437. Path Sum I &II&III

112.Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

My Solutions:

public boolean hasPathSum(TreeNode root, int targetSum) {
    if (root == null) return false;
    if (root.left == null && root.right == null) return targetSum == root.val;
    return (hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val));
}

113.Path Sum II

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Example 1:

My Solutions:

和112类似,但是需要记录path。因此在dfs的时候,需要带上list,存入走过的路径的节点。

  • dfs/recursive:注意在dfs一个root的两边之后,需要删除list里最后一个节点。这是因为list里记录了走过的每一个节点,但是如果一个节点并不是最后加到最终结果里面去的路径,需要把沿路的节点删除掉。

也可以用bfs/iteratvie 的方法

437.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).

Example 1:

My Solutions:

这道题不再需要从root出发,也不用一定要到叶子节点,只要路上有满足要求的路径,就算作满足条件的路径。所以一颗以root为根的树,其路径和等于sum的路径个数可由以下三部分组成:

1.路径以root 开头;2.路径不以root开头

  • 2.1左子树中等于sum的路径个数

  • 2.2右子树中等于sum的路径个数

方法1:

方法2: (2023年无法通过test,因为数字太大)

[1000000000,1000000000,null,294967296,null,1000000000,null,1000000000,null,1000000000]

0

Space: O(n) due to recursion.

Time: O(n^2) in the worst case (no branching); O(nlogn) in the best case (balanced tree).

Last updated