美文网首页
剑指 Offer II 049. 从根节点到叶节点的路径数字之和

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

作者: 邦_ | 来源:发表于2022-06-29 09:25 被阅读0次
    
    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
    
    
    
        }
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:剑指 Offer II 049. 从根节点到叶节点的路径数字之和

          本文链接:https://www.haomeiwen.com/subject/snzgertx.html