/**
* #[derive(PartialEq, Eq, Debug, Clone)]
* pub struct TreeNode {
* pub val: i32,
* pub left: Option<Box<TreeNode>>,
* pub right: Option<Box<TreeNode>>,
* }
*
* impl TreeNode {
* #[inline]
* fn new(val: i32) -> Self {
* TreeNode {
* val: val,
* left: None,
* right: None,
* }
* }
* }
*/
struct Solution{
}
impl Solution {
fn new() -> Self {
Solution{}
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return TreeNode类
*/
pub fn sortedArrayToBST(&self, nums: Vec<i32>) -> Option<Box<TreeNode>> {
return Solution::dfs(self,&nums, 0, nums.len() as i32 -1);
}
fn dfs(&self, nums:& Vec<i32>, b:i32, e:i32) ->Option<Box<TreeNode>> {
if b > e {
return None;
}
let mid = b + (e-b)/2 + (e-b)%2;
let mut node = Box::new(TreeNode::new(nums[mid as usize]));
node.left = Solution::dfs(self, nums, b, mid-1);
node.right = Solution::dfs(self, nums, mid+1, e);
return Some(node);
}
}