|
@@ -0,0 +1,56 @@
|
|
|
|
+struct Solution;
|
|
|
|
+
|
|
|
|
+use crate::solutions::TreeNode;
|
|
|
|
+use std::rc::Rc;
|
|
|
|
+use std::cell::RefCell;
|
|
|
|
+
|
|
|
|
+impl Solution {
|
|
|
|
+ pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
|
|
|
+ let mut res = 0;
|
|
|
|
+ Solution::helper(root, 0, &mut res);
|
|
|
|
+ res
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ fn helper(root: Option<Rc<RefCell<TreeNode>>>, pre: i32, res: &mut i32) {
|
|
|
|
+ if let Some(node) = root {
|
|
|
|
+ let left = node.borrow().left.clone();
|
|
|
|
+ let right = node.borrow().right.clone();
|
|
|
|
+ let val = node.borrow().val;
|
|
|
|
+ let cur = 10 * pre + val;
|
|
|
|
+ if left.is_none() && right.is_none() {
|
|
|
|
+ *res += cur;
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if left.is_some() {
|
|
|
|
+ Solution::helper(left, cur, res);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if right.is_some() {
|
|
|
|
+ Solution::helper(right, cur, res);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ } else {
|
|
|
|
+ return;
|
|
|
|
+
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+#[cfg(test)]
|
|
|
|
+mod tests {
|
|
|
|
+ use super::*;
|
|
|
|
+ use crate::solutions::vec_to_tree;
|
|
|
|
+
|
|
|
|
+ #[test]
|
|
|
|
+ fn test_sum_numbers() {
|
|
|
|
+ let nums = vec![Some(4), Some(9), Some(0), Some(5), Some(1)];
|
|
|
|
+ let root = vec_to_tree(nums);
|
|
|
|
+ let res = Solution::sum_numbers(root);
|
|
|
|
+ assert_eq!(res, 1026);
|
|
|
|
+ }
|
|
|
|
+}
|