We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 84274c0 commit b56124aCopy full SHA for b56124a
1 file changed
lowest-common-ancestor-of-a-binary-search-tree/DaleSeo.rs
@@ -0,0 +1,30 @@
1
+// TC: O(h)
2
+// SC: O(1)
3
+use std::cell::RefCell;
4
+use std::rc::Rc;
5
+
6
+impl Solution {
7
+ pub fn lowest_common_ancestor(
8
+ root: Option<Rc<RefCell<TreeNode>>>,
9
+ p: Option<Rc<RefCell<TreeNode>>>,
10
+ q: Option<Rc<RefCell<TreeNode>>>,
11
+ ) -> Option<Rc<RefCell<TreeNode>>> {
12
+ let p_val = p?.borrow().val;
13
+ let q_val = q?.borrow().val;
14
+ let mut current = root;
15
16
+ while let Some(node) = current {
17
+ let node_ref = node.borrow();
18
+ if p_val < node_ref.val && q_val < node_ref.val {
19
+ current = node_ref.left.clone();
20
+ } else if p_val > node_ref.val && q_val > node_ref.val {
21
+ current = node_ref.right.clone();
22
+ } else {
23
+ drop(node_ref);
24
+ return Some(node);
25
+ }
26
27
28
+ None
29
30
+}
0 commit comments