演算法練習--LeetCode--129. Sum Root to Leaf Numbers; Runtime: 8 ms100%

Crazy凡發表於2019-04-13

129. Sum Root to Leaf Numbers

Medium Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
   1
  / \
 2   3
Output: 25
複製程式碼

Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore, sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1]
   4
  / \
 9   0
/ \
5   1
Output: 1026
複製程式碼

Explanation: The root-to-leaf path 4->9->5 represents the number 495. The root-to-leaf path 4->9->1 represents the number 491. The root-to-leaf path 4->0 represents the number 40. Therefore, sum = 495 + 491 + 40 = 1026.


題目大意: 將一棵樹從root -> leaf的一個遍歷當成一個整數;求各條 root -> leaf遍歷的和; 簡單的樹的遍歷;下面給出兩種思路:

  • 遞迴
  • 迴圈

程式碼如下(Swift5):

class Solution {
    // 遞迴
    // Runtime: 8 ms, faster than 100.00% of Swift online submissions for Sum Root to Leaf Numbers.
    // Memory Usage: 19.1 MB, less than 25.00% of Swift online submissions for Sum Root to Leaf Numbers.
    func sumNumbers(_ root: TreeNode?) -> Int {
        var result = 0
        func next(_ previous: Int, node: TreeNode?) {
            guard let node = node else { return }
            let current = previous * 10 + node.val
            if node.left == nil && node.right == nil {
                result += current
            } else {
                next(current, node: node.left)
                next(current, node: node.right)
            }
        }
        next(0, node: root)
        return result
    }
    
    // 迴圈
    // Runtime: 12 ms, faster than 89.86% of Swift online submissions for Sum Root to Leaf Numbers.
    // Memory Usage: 18.9 MB, less than 50.00% of Swift online submissions for Sum Root to Leaf Numbers.
    func sumNumbers_2(_ root: TreeNode?) -> Int {
        typealias keyNode = (previous: Int, node: TreeNode)
        
        guard let root = root else { return 0 }
        
        var result = 0
        var keyNodes: [keyNode] = [(0, root)]
        while !keyNodes.isEmpty {
            
            var temp: [keyNode] = []
            for keyNode in keyNodes {
                let node = keyNode.node
                let current = keyNode.previous * 10 + node.val
                
                if node.left == nil, node.right == nil {
                    result += current
                } else {
                    if let left = node.left {
                        temp.append((current, left))
                    }
                    if let right = node.right {
                        temp.append((current, right))
                    }
                }
            }
            keyNodes = temp
        }
        return result
    }
}
複製程式碼

相關文章