简繁EN

LeetCodeNo. 102

【LeetCode with Python】 129. Sum Root to Leaf Numbers

目錄

題目

原題頁面:https://leetcode.com/problems/sum-root-to-leaf-numbers/
題目型別:Tree, Depth-first Search
難度評價:Medium
類似題目:(E) Path Sum, (H) Binary Tree Maximum Path Sum

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.

For example,

1
2
3
  1
/ \
2 3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.


分析

從根節點到葉子節點的路徑代表一個數值,找出所有的這些數值然後累加得到一個和。
搜尋演算法可以用來找可行解,或者找出全部解。找可行解的時候可以用深度優先遍歷DFS,或者廣度優先遍歷BFS。而這個題目則是找出全部解,然後累加全部解。而搜尋演算法找全部解時的遞迴解法一般也是兩種:自底向上和自頂向下(自己命名的,哈哈)。
就拿這道題來說,自底向上,也就是當遞迴到葉子節點後,在遞迴退棧的過程中,讓左子樹遞迴返回的數加上右子樹遞迴返回的數。
注意解法中其實用到了乘法分配律,否則每次“歸”的時候,就得向上層返回一個數的列表,且越接近root的時候列表會越長。或者記錄一個物件內的成員變數,當遍歷到葉子節點時,每個葉子節點將到達自身所形成的路徑的值加上到成員變數上。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def doSumNumbers(self, root, val):
if None == root.left and None == root.right:
return val * 10 + root.val
left = 0
right = 0
if None != root.left:
left = self.doSumNumbers(root.left, val * 10 + root.val)
if None != root.right:
right = self.doSumNumbers(root.right, val * 10 + root.val)
return left + right

# @param root, a tree node
# @return an integer
def sumNumbers(self, root):
if None == root:
return 0
return self.doSumNumbers(root, 0)

本文地址:https://xnerv.wang/zh-tw/leetcode-sum-root-to-leaf-numbers/