1
+ //! Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
2
+ //!
3
+ //! An example is the root-to-leaf path 1->2->3 which represents the number 123.
4
+ //!
5
+ //! Find the total sum of all root-to-leaf numbers.
6
+ //!
7
+ //! Note: A leaf is a node with no children.
8
+ //!
9
+ //! Example:
10
+ //!
11
+ //! ```shell
12
+ //! Input: [1,2,3]
13
+ //! 1
14
+ //! / \
15
+ //! 2 3
16
+ //! Output: 25
17
+ //! Explanation:
18
+ //! The root-to-leaf path 1->2 represents the number 12.
19
+ //! The root-to-leaf path 1->3 represents the number 13.
20
+ //! Therefore, sum = 12 + 13 = 25.
21
+ //! Example 2:
22
+ //! ```
23
+ //!
24
+ //! ```shell
25
+ //! Input: [4,9,0,5,1]
26
+ //! 4
27
+ //! / \
28
+ //! 9 0
29
+ //! / \
30
+ //! 5 1
31
+ //! Output: 1026
32
+ //! Explanation:
33
+ //! The root-to-leaf path 4->9->5 represents the number 495.
34
+ //! The root-to-leaf path 4->9->1 represents the number 491.
35
+ //! The root-to-leaf path 4->0 represents the number 40.
36
+ //! Therefore, sum = 495 + 491 + 40 = 1026.
37
+ //! ```
38
+ //!
39
+ //! Link:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers
40
+
41
+ use super :: * ;
42
+ struct Solution { }
43
+
44
+
45
+
46
+ impl Solution {
47
+ pub fn helper ( root : Option < Rc < RefCell < TreeNode > > > ) -> Vec < Vec < i32 > > {
48
+ if let Some ( v) = root {
49
+ let val = RefCell :: borrow ( & v) . val ;
50
+ let mut left = Solution :: helper ( RefCell :: borrow ( & v) . left . clone ( ) ) ;
51
+ let mut right = Solution :: helper ( RefCell :: borrow ( & v) . right . clone ( ) ) ;
52
+ if left. len ( ) == 0 && right. len ( ) == 0 {
53
+ left. push ( vec ! ( val) )
54
+ } else {
55
+ left. iter_mut ( ) . for_each ( |x| x. push ( val) ) ;
56
+ right. iter_mut ( ) . for_each ( |x| x. push ( val) ) ;
57
+ left. extend ( right) ;
58
+ }
59
+ left
60
+ } else {
61
+ vec ! ( )
62
+ }
63
+ }
64
+
65
+ pub fn sum_numbers ( root : Option < Rc < RefCell < TreeNode > > > ) -> i32 {
66
+ fn helper2 ( r : Option < Rc < RefCell < TreeNode > > > , p : i32 ) -> Vec < i32 > {
67
+ let mut nums = vec ! ( ) ;
68
+ if let Some ( v) = r {
69
+ let val = RefCell :: borrow ( & v) . val + 10 * p ;
70
+ let left_child = RefCell :: borrow ( & v) . left . clone ( ) ;
71
+ let right_child = RefCell :: borrow ( & v) . right . clone ( ) ;
72
+ if left_child. is_none ( ) && right_child. is_none ( ) {
73
+ nums. push ( val) ;
74
+ } else {
75
+ nums. extend ( Solution :: helper2 ( left_child, val) ) ;
76
+ nums. extend ( Solution :: helper2 ( right_child, val) ) ;
77
+ }
78
+ }
79
+ nums
80
+ }
81
+ h ( root, 0 ) . iter ( ) . sum ( )
82
+ }
83
+ }
84
+
85
+
86
+ #[ cfg( test) ]
87
+ mod tests {
88
+ use super :: * ;
89
+
90
+ #[ test]
91
+ fn test_1 ( ) {
92
+ assert_eq ! ( Solution :: sum_numbers( tree!( 4 , 9 , 0 , 5 , 1 ) ) , 1026 ) ;
93
+ assert_eq ! ( Solution :: sum_numbers( tree!( 1 , 2 , 3 ) ) , 25 )
94
+ }
95
+ }
0 commit comments