|
| 1 | +/** |
| 2 | + * [129] Sum Root to Leaf Numbers |
| 3 | + * |
| 4 | + * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. |
| 5 | + * |
| 6 | + * An example is the root-to-leaf path 1->2->3 which represents the number 123. |
| 7 | + * |
| 8 | + * Find the total sum of all root-to-leaf numbers. |
| 9 | + * |
| 10 | + * Note: A leaf is a node with no children. |
| 11 | + * |
| 12 | + * Example: |
| 13 | + * |
| 14 | + * |
| 15 | + * Input: [1,2,3] |
| 16 | + * 1 |
| 17 | + * / \ |
| 18 | + * 2 3 |
| 19 | + * Output: 25 |
| 20 | + * Explanation: |
| 21 | + * The root-to-leaf path 1->2 represents the number 12. |
| 22 | + * The root-to-leaf path 1->3 represents the number 13. |
| 23 | + * Therefore, sum = 12 + 13 = 25. |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * |
| 28 | + * Input: [4,9,0,5,1] |
| 29 | + * 4 |
| 30 | + * / \ |
| 31 | + * 9 0 |
| 32 | + * / \ |
| 33 | + * 5 1 |
| 34 | + * Output: 1026 |
| 35 | + * Explanation: |
| 36 | + * The root-to-leaf path 4->9->5 represents the number 495. |
| 37 | + * The root-to-leaf path 4->9->1 represents the number 491. |
| 38 | + * The root-to-leaf path 4->0 represents the number 40. |
| 39 | + * Therefore, sum = 495 + 491 + 40 = 1026. |
| 40 | + * |
| 41 | + */ |
| 42 | +pub struct Solution {} |
| 43 | +use super::util::tree::{TreeNode, to_tree}; |
| 44 | + |
| 45 | +// submission codes start here |
| 46 | + |
| 47 | +use std::rc::Rc; |
| 48 | +use std::cell::RefCell; |
| 49 | +use std::collections::VecDeque; |
| 50 | +impl Solution { |
| 51 | + pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { |
| 52 | + let mut sum = 0; |
| 53 | + if root.is_none() { return sum } |
| 54 | + let mut deq = VecDeque::new(); |
| 55 | + deq.push_back((root.clone(), 0)); |
| 56 | + while let Some(item) = deq.pop_front() { |
| 57 | + if let (Some(node), acc) = item { |
| 58 | + let acc = acc * 10 + node.borrow().val; |
| 59 | + if node.borrow().left.is_none() && node.borrow().right.is_none() { |
| 60 | + sum += acc; |
| 61 | + continue; |
| 62 | + } |
| 63 | + deq.push_back((node.borrow().left.clone(), acc)); |
| 64 | + deq.push_back((node.borrow().right.clone(), acc)); |
| 65 | + } |
| 66 | + } |
| 67 | + sum |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +// submission codes end |
| 72 | + |
| 73 | +#[cfg(test)] |
| 74 | +mod tests { |
| 75 | + use super::*; |
| 76 | + |
| 77 | + #[test] |
| 78 | + fn test_129() { |
| 79 | + assert_eq!(Solution::sum_numbers(tree![1,2,3]), 25); |
| 80 | + assert_eq!(Solution::sum_numbers(tree![4,9,0,5,1]), 1026); |
| 81 | + } |
| 82 | +} |
0 commit comments