129 Sum Root to Leaf Numbers
129. Sum Root to Leaf Numbers
1. Question
Given a binary tree containing digits from0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3
which represents the number123
.
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path1->2
represents the number12
.
The root-to-leaf path1->3
represents the number13
.
Return the sum = 12 + 13 =25
.
2. Implementation
(1) DFS recursion
(2) BFS
3. Time & Space Complexity
DFS recursion: 时间复杂度: O(n), 空间复杂度: O(n)
BFS: 时间复杂度: O(n), 空间复杂度: O(w), w是树里有最多node的一层的node个数
Last updated
Was this helpful?