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
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.
Hide Tags Tree Depth-first Search
Show Similar Problems
解法1: DFS , O(N) Space + O(N) Time
题意是对每一个path做一个操作(记录成一个数字),容易想到用DFS来遍历整棵数。
遍历的时候用一个vector存储每一个数字,最后对vector求一下和。
C++
Java
解法2: DFS , O(1) Space + O(N) Time
实际上不需要用一个vector来存储见到的数字。
C++