20240609 Finished

This commit is contained in:
jackfiled 2024-06-09 11:26:53 +08:00
parent 58a24ad3e9
commit c74f8010d6
2 changed files with 73 additions and 1 deletions

View File

@ -144,3 +144,4 @@ mod p100_same_tree;
mod p226_invert_binary_tree; mod p226_invert_binary_tree;
mod p101_symmetric_tree; mod p101_symmetric_tree;
mod p114_flatten_binary_tree_to_linked_list; mod p114_flatten_binary_tree_to_linked_list;
mod p112_path_sum;

View File

@ -0,0 +1,71 @@
/**
* [112] Path Sum
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
// submission codes start here
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
fn dfs(node: &Rc<RefCell<TreeNode>>, current_sum: i32, target_sum: i32) -> bool {
// 到达叶子节点
if node.borrow().left.is_none() && node.borrow().right.is_none() {
return current_sum + node.borrow().val == target_sum;
}
if let Some(left) = &node.borrow().left {
if Self::dfs(left, current_sum + node.borrow().val, target_sum) {
return true;
}
}
if let Some(right) = &node.borrow().right {
if Self::dfs(right, current_sum + node.borrow().val, target_sum) {
return true;
}
}
false
}
pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool {
if let Some(root) = root {
return Self::dfs(&root, 0, target_sum);
}
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_112() {
}
}