algo/rust/24_binary_tree/insert_in_binary_tree.rs
Caitlin Gao 89d6013c88 feat(geektime_algo): add 24 binary tree
insert in binary tree, search in binary tree, max depth in binary tree
2019-07-25 21:56:56 +08:00

20 lines
608 B
Rust

// https://leetcode.com/problems/insert-into-a-binary-search-tree/
use super::util::tree::{TreeNode, to_tree};
pub fn insert_into_bst(root: Option<Rc<RefCell<TreeNode>>>, val: i32) -> Option<Rc<RefCell<TreeNode>>> {
insert(&root, val);
root
}
fn insert(node: &Option<Rc<RefCell<TreeNode>>>, val: i32) {
if let Some(n) = node {
let mut n = n.borrow_mut();
let target = if val > n.val { &mut n.right } else { &mut n.left };
if target.is_some() {
return insert(target, val);
}
*target = Some(Rc::new(RefCell::new(TreeNode::new(val))));
}
}