1. 程式人生 > >【LeetCode 中等題】59-求根到葉子節點數字之和

【LeetCode 中等題】59-求根到葉子節點數字之和

題目描述:給定一個二叉樹,它的每個結點都存放一個 0-9 的數字,每條從根到葉子節點的路徑都代表一個數字。例如,從根到葉子節點路徑 1->2->3 代表數字 123。計算從根到葉子節點生成的所有數字之和。

說明: 葉子節點是指沒有子節點的節點。

示例 1:

輸入: [1,2,3]
    1
   / \
  2   3
輸出: 25
解釋:
從根到葉子節點路徑 1->2代表數字 12.從根到葉子節點路徑 1->3代表數字 13.因此,數字總和 = 12 + 13 = 25.

示例 2:

輸入: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
輸出: 1026
解釋:
從根到葉子節點路徑 4->9->5代表數字 495.從根到葉子節點路徑 4->9->1代表數字 491.根到葉子節點路徑 4->0代表數字 40.因此,數字總和 = 495 + 491 + 40 = 1026.

解法1。DFS做法,和求二叉樹路徑之和是一個思路,只是邏輯略微不一樣,遇到葉子結點就把path放到res裡,最後遍歷res,求和,注意回溯要pop,還有型別轉換的問題。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        path = []
        res = []
        self.helper(root, path, res)
        fi = 0
        for path in res:
            num = int(''.join(path))
            fi += num
        return fi
    
    def helper(self, root, path, res):
        if not root:
            return
        path.append(str(root.val))
        if not root.left and not root.right:
            res.append(path[:])
        self.helper(root.left, path, res)
        self.helper(root.right, path, res)
        path.pop()

# 參照做法2,可知上段程式碼可以優化一下,path可以改成一個數字,就是截至目前的累積的數字
class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        res = []
        self.helper(root, root.val, res)
        return sum(res)
    
    def helper(self, root, val, res):
        if not root:
            return
        if not root.left and not root.right:
            res.append(val)
            return
        if root.left:
            self.helper(root.left, val*10+root.left.val, res)
        if root.right:
            self.helper(root.right, val*10+root.right.val, res)

解法2。用迴圈,思路和遞迴基本一致,不過是BFS,用stack存放要被遍歷的節點,但stack維護的元素內容是節點和截至目前的數字構成的二元組,res記錄葉子節點的數字,也就是遍歷到該葉子結點得到的數,返回res內數的和。

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        stack = [(root, root.val)]
        res = []
        while stack:
            node, val = stack.pop(0)
            if not node.left and not node.right:
                res.append(val)
            else:
                if node.left:
                    stack.append((node.left, val*10+node.left.val))
                if node.right:
                    stack.append((node.right, val*10+node.right.val))
        return sum(res)