Leetcode 437 Title: Total Path III (recursive - Simple)

Subject description:

Given a binary tree, each node that are stored with an integer value.

Total number of paths to find the path and is equal to the given value.

Path does not require starting from the root, do not need to end in a leaf node, but the path direction must be down (only node from parent to child node).

No more than 1000 binary tree nodes, and the node value range is [-1000000,1000000] integer.

Ideas Analysis: problem solution from ( https://leetcode-cn.com/problems/path-sum-iii/solution/leetcode-437-path-sum-iii-by-li-xin-lei/ )

Beginning of the path may not be the root node, may not be the end of a leaf node, is not it a bit complicated?
If the problem is this: to find out the root node as the start, any node can be used as the end, and the node and path sum of the number on the path;
is not preorder traversal of a binary tree can get over all this path? Yes;
if this issue is resolved, then the original problem can be decomposed into a plurality of the problem;
is not the same issue several segments, but the segments into a binary tree;
in the settlement of all paths to the root node after, to find a child to the root of the left and right of all children to start the path, three nodes constitute a recursive structure;

Code:

/ ** 
 * A for binary Tree Node Definition. 
 * Public class the TreeNode { 
 * int Val; 
 * the TreeNode left; 
 * the TreeNode right; 
 * the TreeNode (int X) {X = Val;} 
 *} 
 * / 
class Solution { 
   / ** 
     * seek to root for the root of the binary tree, and all paths for the sum of; 
     * the beginning of the path is not necessarily the root, not necessarily the end of leaf nodes; 
     * @param root 
     * @param sum 
     * @return 
     * / 
    public int pathSum ( the root the TreeNode, int SUM) { 

        IF (the root == null) { 
            return 0; 
        } 

        return Paths (the 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;
    }
}
Time complexity: O (n), n the number of nodes of the tree;
Space complexity: O (h), h is the height of the tree;

Guess you like

Origin www.cnblogs.com/ysw-go/p/12033847.html