[Swift]LeetCode1022. 从根到叶的二进制数之和 | Sum of Root To Leaf Binary Numbers

Given a binary tree, each node has value 0 or 1.  Each root-to-leaf path represents a binary number starting with the most significant bit.  For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers modulo 10^9 + 7.

Example 1:

Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 

Note:

  1. The number of nodes in the tree is between 1 and 1000.
  2. node.val is 0 or 1.

给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。

对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

以 10^9 + 7 为模,返回这些数字之和。 

示例:

输入:[1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 

提示:

  1. 树中的结点数介于 1 和 1000 之间。
  2. node.val 为 0 或 1 。

Runtime: 24 ms
Memory Usage: 19 MB
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var mod:Int = 1000000007
16     var ans:Int = 0
17     func sumRootToLeaf(_ root: TreeNode?) -> Int {
18         ans = 0
19         dfs(root, 0)
20         return ans % mod
21     }
22     
23     func dfs(_ cur: TreeNode?,_ v:Int)
24     {
25         if cur == nil {return}
26         if cur?.left == nil && cur?.right == nil
27         {
28             ans += v*2 + cur!.val
29             return
30         }
31         dfs(cur?.left, (v*2 + cur!.val) % mod)
32         dfs(cur?.right, (v*2 + cur!.val) % mod)
33         
34     }
35 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10667991.html