- use std::rc::Rc;
- use std::cell::RefCell;
-
- // Definition for a binary tree node.
- #[derive(Debug, PartialEq, Eq)]
- pub struct TreeNode {
- pub val: i32,
- pub left: Option
>>, - pub right: Option
>>, - }
- impl TreeNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- TreeNode {
- val,
- left: None,
- right: None,
- }
- }
- }
- // 递归dfs
- pub fn has_path_sum(root: Option
>>, target_sum: i32) -> bool { - fn dfs(node: &Option
>>, target_sum: i32) -> bool { - if let Some(node) = node {
- let node = node.borrow();
- let remaining_sum = target_sum - node.val;
- if node.left.is_none() && node.right.is_none() {
- return remaining_sum == 0;
- }
- dfs(&node.left, remaining_sum) || dfs(&node.right, remaining_sum)
- } else {
- false
- }
- }
-
- dfs(&root, target_sum)
- }
- // 迭代dfs
- pub fn has_path_sum2(root: Option
>>, target_sum: i32) -> bool { - if root.is_none() {
- return false;
- }
-
- let mut stack = vec![(root.clone(), target_sum)];
-
- while let Some((node, remaining_sum)) = stack.pop() {
- if let Some(node) = node {
- let node = node.borrow();
- let new_sum = remaining_sum - node.val;
-
- if node.left.is_none() && node.right.is_none() && new_sum == 0 {
- return true;
- }
-
- if let Some(ref left) = node.left {
- stack.push((Some(Rc::clone(left)), new_sum));
- }
-
- if let Some(ref right) = node.right {
- stack.push((Some(Rc::clone(right)), new_sum));
- }
- }
- }
-
- false
- }
- use std::collections::VecDeque;
- // bfs
- pub fn has_path_sum3(root: Option
>>, target_sum: i32) -> bool { - if root.is_none() {
- return false;
- }
-
- let mut queue = VecDeque::new();
- queue.push_back((root.clone(), target_sum));
-
- while let Some((node, remaining_sum)) = queue.pop_front() {
- if let Some(node) = node {
- let node = node.borrow();
- let new_sum = remaining_sum - node.val;
-
- if node.left.is_none() && node.right.is_none() && new_sum == 0 {
- return true;
- }
-
- if let Some(ref left) = node.left {
- queue.push_back((Some(Rc::clone(left)), new_sum));
- }
-
- if let Some(ref right) = node.right {
- queue.push_back((Some(Rc::clone(right)), new_sum));
- }
- }
- }
-
- false
- }
- fn main() {}