75. The algorithm is simple and swift sum path III

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, you 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.

Example:

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

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

Returns 3. 8 have equal path:

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

 

solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */
class Solution {
    func pathSum(_ root: TreeNode?, _ sum: Int) -> Int {
        if(root == nil){
            return 0;
        }
        return sums(root,sum)+pathSum(root!.left,sum)+pathSum(root!.right,sum);
    }
    
    func  sums(_ root: TreeNode?, _ sum: Int) -> Int{
    if(root == nil){
    return 0;
    }
        let left = sums(root?.left,sum - root!.val)
        let right = sums(root?.right,sum - root!.val)
    
        if(root!.val == sum){
        return right+left+1;
    }else{
        return right+left;
    }
    
    }
}

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/93459464