From e1eb4ffa160ed6dbff3e69d3a43abee5f76e571f Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 3 Jun 2024 11:27:57 +0800 Subject: [PATCH] 20240603 Finished --- src/problem/mod.rs | 3 +- .../p104_maximum_depth_of_binary_tree.rs | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 src/problem/p104_maximum_depth_of_binary_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index d4e1069..a5e61e1 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -138,4 +138,5 @@ mod p71_simplify_path; mod p155_min_stack; mod p150_evaluate_reverse_polish_notation; mod p224_basic_calculator; -mod p21_merge_two_sorted_lists; \ No newline at end of file +mod p21_merge_two_sorted_lists; +mod p104_maximum_depth_of_binary_tree; \ No newline at end of file diff --git a/src/problem/p104_maximum_depth_of_binary_tree.rs b/src/problem/p104_maximum_depth_of_binary_tree.rs new file mode 100644 index 0000000..46c1a4e --- /dev/null +++ b/src/problem/p104_maximum_depth_of_binary_tree.rs @@ -0,0 +1,70 @@ +/** + * [104] Maximum Depth of Binary Tree + */ +pub struct Solution {} + +use crate::util::tree::{to_tree, TreeNode}; + +// submission codes start here + +// 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 +// } +// } +// } +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; +impl Solution { + pub fn max_depth(root: Option>>) -> i32 { + let mut queue = VecDeque::new(); + + let mut depth = 0; + + if let Some(node) = root { + queue.push_back(node); + } + + while !queue.is_empty() { + let level = queue.len(); + depth += 1; + + for i in 0..level { + let node = queue.pop_front().unwrap(); + + if let Some(left) = &node.borrow().left { + queue.push_back(Rc::clone(left)); + }; + + if let Some(right) = &node.borrow().right { + queue.push_back(Rc::clone(right)); + }; + } + } + + depth + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_104() {} +}