Skip to content

Commit bcd2513

Browse files
committed
solve #112
1 parent 158eca3 commit bcd2513

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,4 @@ mod n0108_convert_sorted_array_to_binary_search_tree;
112112
mod n0109_convert_sorted_list_to_binary_search_tree;
113113
mod n0110_balanced_binary_tree;
114114
mod n0111_minimum_depth_of_binary_tree;
115+
mod n0112_path_sum;

src/n0112_path_sum.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* [112] Path Sum
3+
*
4+
* Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
5+
*
6+
* Note: A leaf is a node with no children.
7+
*
8+
* Example:
9+
*
10+
* Given the below binary tree and sum = 22,
11+
*
12+
*
13+
* 5
14+
* / \
15+
* 4 8
16+
* / / \
17+
* 11 13 4
18+
* / \ \
19+
* 7 2 1
20+
*
21+
*
22+
* return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
23+
*
24+
*/
25+
pub struct Solution {}
26+
use super::util::tree::{TreeNode, to_tree};
27+
28+
// submission codes start here
29+
30+
use std::rc::Rc;
31+
use std::cell::RefCell;
32+
use std::collections::VecDeque;
33+
impl Solution {
34+
pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, sum: i32) -> bool {
35+
if root.is_none() { return false }
36+
let mut deq = VecDeque::new();
37+
deq.push_back((0, root.clone()));
38+
while !deq.is_empty() {
39+
if let Some((acc, Some(node))) = deq.pop_front() {
40+
let acc = acc + node.borrow().val;
41+
if node.borrow().left.is_none() && node.borrow().right.is_none() {
42+
if acc == sum { return true }
43+
} else {
44+
deq.push_back((acc, node.borrow().left.clone()));
45+
deq.push_back((acc, node.borrow().right.clone()));
46+
}
47+
}
48+
}
49+
false
50+
}
51+
}
52+
53+
// submission codes end
54+
55+
#[cfg(test)]
56+
mod tests {
57+
use super::*;
58+
59+
#[test]
60+
fn test_112() {
61+
assert_eq!(Solution::has_path_sum(tree![5,4,8,11,null,13,4,7,2,null,null,null,1], 22), true);
62+
}
63+
}

0 commit comments

Comments
 (0)