Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created April 14, 2019 14:44
Show Gist options
  • Save wszdwp/e583f74b8f25b7f9f7bf59778cb36e38 to your computer and use it in GitHub Desktop.
Save wszdwp/e583f74b8f25b7f9f7bf59778cb36e38 to your computer and use it in GitHub Desktop.
129. Sum Root to Leaf Numbers
/**
* 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 sumNumbers(_ root: TreeNode?) -> Int {
if root == nil { return 0 }
var sum = [0]
sumRootToLeft(root, cur: 0, sum: &sum)
return sum[0]
}
func sumRootToLeft(_ root: TreeNode?, cur: Int, sum: inout [Int]) {
if (root == nil) { return }
if root!.left == nil && root!.right == nil {
let curNum = cur * 10 + root!.val
sum[0] += curNum
return
}
if root!.left != nil {
sumRootToLeft(root!.left, cur: cur * 10 + root!.val, sum: &sum)
}
if root!.right != nil {
sumRootToLeft(root!.right, cur: cur * 10 + root!.val, sum: &sum)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment