From 59e91d5da4e7b180cf4651675f64a7e57fb5a7ae Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 25 Feb 2024 14:24:54 +0800 Subject: [PATCH] 20240225 Finished --- src/problem/mod.rs | 3 +- ...common_ancestor_of_a_binary_search_tree.rs | 58 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 0ce5d94..3af29c7 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -51,4 +51,5 @@ mod p102_binary_tree_level_order_traversal; mod p107_binary_tree_level_order_traversal_ii; mod p103_binary_tree_zigzag_level_order_traversal; mod p105_construct_binary_tree_from_preorder_and_inorder_traversal; -mod p106_construct_binary_tree_from_inorder_and_postorder_traversal; \ No newline at end of file +mod p106_construct_binary_tree_from_inorder_and_postorder_traversal; +mod p235_lowest_common_ancestor_of_a_binary_search_tree; \ No newline at end of file diff --git a/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs b/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs new file mode 100644 index 0000000..fe3d894 --- /dev/null +++ b/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs @@ -0,0 +1,58 @@ +/** + * [235] Lowest Common Ancestor of a Binary Search Tree + */ +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>>, +// pub right: Option>>, +// } +// +// 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 { + pub fn lowest_common_ancestor(root: Option>>, p: Option>>, q: Option>>) -> Option>> { + let (root, p, q) = (root?, p?, q?); + let mut ancestor = root; + + loop { + ancestor = if p.borrow().val < ancestor.borrow().val && q.borrow().val < ancestor.borrow().val { + Rc::clone(&ancestor.borrow().left.as_ref().unwrap()) + } else if (p.borrow().val > ancestor.borrow().val && q.borrow().val > ancestor.borrow().val ) { + Rc::clone(&ancestor.borrow().right.as_ref().unwrap()) + } else { + break; + } + } + + Some(ancestor) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_235() { + } +}