題目
原題頁面: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-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.Find the total sum of all root-to-leaf numbers.
For example,
1
2
3 1
/ \
2 3The root-to-leaf path
1->2represents the number12.
The root-to-leaf path1->3represents the number13.Return the sum = 12 + 13 =
25.
分析
從根節點到葉子節點的路徑代表一個數值,找出所有的這些數值然後累加得到一個和。
搜尋演算法可以用來找可行解,或者找出全部解。找可行解的時候可以用深度優先遍歷DFS,或者廣度優先遍歷BFS。而這個題目則是找出全部解,然後累加全部解。而搜尋演算法找全部解時的遞迴解法一般也是兩種:自底向上和自頂向下(自己命名的,哈哈)。
就拿這道題來說,自底向上,也就是當遞迴到葉子節點後,在遞迴退棧的過程中,讓左子樹遞迴返回的數加上右子樹遞迴返回的數。
注意解法中其實用到了乘法分配律,否則每次“歸”的時候,就得向上層返回一個數的列表,且越接近root的時候列表會越長。或者記錄一個物件內的成員變數,當遍歷到葉子節點時,每個葉子節點將到達自身所形成的路徑的值加上到成員變數上。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-sum-root-to-leaf-numbers/
