Browse Source

feat: sum_root_to_leaf_nums

Zhang Li 1 year ago
parent
commit
9e95df2918
2 changed files with 57 additions and 0 deletions
  1. 1 0
      src/solutions/tree/mod.rs
  2. 56 0
      src/solutions/tree/sum_root_to_leaf_nums.rs

+ 1 - 0
src/solutions/tree/mod.rs

@@ -15,3 +15,4 @@ mod minimum_depth_of_binary_tree;
 mod path_sum;
 mod path_sum2;
 mod binary_tree_maximum_path_sum;
+mod sum_root_to_leaf_nums;

+ 56 - 0
src/solutions/tree/sum_root_to_leaf_nums.rs

@@ -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);
+    }
+}