You are given the root
of a binary tree containing digits from 0
to 9
only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3
represents the number 123
.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
root = [1,2,3]
1->2
represents the number 12
.1->3
represents the number 13
.Example 2:
root = [4,9,0,5,1]
4->9->5
represents the number 495
.4->9->1
represents the number 491
.4->0
represents the number 40
.Constraints:
[1, 1000]
.Node.val
<= 9一樣是 DFS,這次多了 path 的概念,沿路要一直記住 path,最後當遇到 leaf 再把整條轉成 int,至於為什麼又有 __init__
的局?因為我不想在 function 裡面帶一堆參數,乾脆給 __init__
帶著就好
走訪過每個點,所以是
這邊比較麻煩的是空間,因為有 path 的紀錄,而每一層都會換一個 path,有點像是