Skip to content

Commit b56124a

Browse files
authored
lowest-common-ancestor-of-a-binary-search-tree (#2622)
1 parent 84274c0 commit b56124a

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

  • lowest-common-ancestor-of-a-binary-search-tree
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)