Skip to content

Commit d362439

Browse files
authored
Merge pull request #2665 from rmrt1n/235
Create 0235-lowest-common-ancestor-of-a-binary-search-tree.rs
2 parents ba78055 + fcb6cba commit d362439

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use std::rc::Rc;
2+
use std::cell::RefCell;
3+
impl Solution {
4+
pub fn lowest_common_ancestor(
5+
root: Option<Rc<RefCell<TreeNode>>>,
6+
p: Option<Rc<RefCell<TreeNode>>>,
7+
q: Option<Rc<RefCell<TreeNode>>>,
8+
) -> Option<Rc<RefCell<TreeNode>>> {
9+
let (p, q) = (p.unwrap().borrow().val, q.unwrap().borrow().val);
10+
let mut root = root;
11+
while let Some(node) = root {
12+
if p > node.borrow().val && q > node.borrow().val {
13+
root = node.borrow().right.clone();
14+
} else if p < node.borrow().val && q < node.borrow().val {
15+
root = node.borrow().left.clone();
16+
} else {
17+
return Some(node.clone());
18+
}
19+
}
20+
unreachable!()
21+
}
22+
}

0 commit comments

Comments
 (0)