LeetCode—437. Path Sum III—Analysis and Code (Java)

LeetCode—437. Path Sum III [Path Sum III]—Analysis and Code [Java]

1. Title

Given a binary tree, each node of it stores an integer value.

Find the path and the total number of paths equal to the given value.

The path does not need to start from the root node or end at the leaf node, but the path direction must be downward (only from the parent node to the child node).

The binary tree does not exceed 1000 nodes, and the node value range is an integer of [-1000000,1000000].

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

返回 3。和等于 8 的路径有:

1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/path-sum-iii
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. DFS recursion

(1) Thinking

Because the path can be any node as the starting node, and the direction is limited to downward, consider that it can be traversed in DFS mode while calculating the total of each path.
In order to facilitate recursion, the difference between the sum of the paths and the sum can be passed and judged directly by whether it is 0.

(2) Code

class Solution {
    
    
    int ans = 0;

    public int pathSum(TreeNode root, int sum) {
    
    
        if (root == null)
            return ans;
        DFS(root, sum);
        if (root.left != null)
            pathSum(root.left, sum);
        if (root.right != null)
            pathSum(root.right, sum);
        return ans;
    }

    public int DFS(TreeNode node, int pSum) {
    
    
        pSum -= node.val;
        if (pSum == 0)
            ans++;
        if (node.left != null)
            DFS(node.left, pSum);
        if (node.right != null)
            DFS(node.right, pSum);
        return pSum;
    }
}

(3) Results

Execution time: 22 ms, beating 76.86% of users
in all Java submissions ; memory consumption: 39.3 MB, beating 91.64% of users in all Java submissions.

Three, other

It is also possible to use an array to record the sum of paths starting from different parent nodes on the way during a DFS traversal, reducing the number of traversals and increasing the consumption of the array.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112640748