LeetCode 1008. Construct Binary Search Tree from Preorder Traversal

Problem Statement


// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
fn compute(v: &Vec<i32>, start: i32, end: i32) -> Option<Rc<RefCell<TreeNode>>> {
if start > end {
return None;
}
if start == end {
let mut node = TreeNode::new(v[start as usize]);
return Some(Rc::new(RefCell::new(node)))
}
let (mut s, mut e) = (start + 1, start + 1);
while e <= end {
if v[e as usize] > v[start as usize] {
break;
}
e += 1;
}
e -= 1;
let mut node = TreeNode::new(v[start as usize]);
node.left = Self::compute(v, s, e);
node.right = Self::compute(v, e + 1, end);
Some(Rc::new(RefCell::new(node)))
}
pub fn bst_from_preorder(preorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
return Self::compute(&preorder, 0, preorder.len() as i32 - 1);
}
}