func sumNumbers(_ root: TreeNode?) -> Int {
var array = Array<TreeNode>()
var numArray = Array<Int>()
var sum = 0
array.append(root!)
numArray.append((root?.val)!)
while !array.isEmpty {
let node = array.removeFirst()
let num = numArray.removeFirst()
if node.left == nil && node.right == nil {
sum += num
}else {
if let left = node.left {
array.append(left)
numArray.append(num * 10 + left.val)
}
if let right = node.right {
array.append(right)
numArray.append(num * 10 + right.val)
}
}
}
return sum
}
网友评论