Skip to content

Commit

Permalink
create 0235-lowest-common-ancestor-of-a-binary-search-tree.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
rmrt1n committed Jun 30, 2023
1 parent af97625 commit fcb6cba
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions rust/0235-lowest-common-ancestor-of-a-binary-search-tree.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn lowest_common_ancestor(
root: Option<Rc<RefCell<TreeNode>>>,
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
let (p, q) = (p.unwrap().borrow().val, q.unwrap().borrow().val);
let mut root = root;
while let Some(node) = root {
if p > node.borrow().val && q > node.borrow().val {
root = node.borrow().right.clone();
} else if p < node.borrow().val && q < node.borrow().val {
root = node.borrow().left.clone();
} else {
return Some(node.clone());
}
}
unreachable!()
}
}

0 comments on commit fcb6cba

Please sign in to comment.