剑指 Offer II 049. 从根节点到叶节点的路径数字之和


func sumNumbers(_ root: TreeNode?) -> Int {
       var array = Array()
       var numArray = Array()
       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



    }





你可能感兴趣的:(剑指 Offer II 049. 从根节点到叶节点的路径数字之和)