Skip to main content
Back to problems
#776
Medium Algorithms

Split bst

Tree Binary Search Tree Recursion Binary Tree
82.2% acceptance
Mar 31, 2026
1092
105
Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where the first subtree has nodes that are all smaller or equal to the target value, while the second subtree has all nodes that are greater than the target value. It is not necessarily the case that the tree contains a node with the value target. Additionally, most of the structure of the original tree should remain. Formally, for any child c with parent p in the original tree, if they are both in the same subtree after the split, then node c should still have the parent p. Return an array of the two roots of the two subtrees in order.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// 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 {
  pub fn split_bst(root: Option<Rc<RefCell<TreeNode>>>, target: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
    match root {
      None => vec![None, None],
      Some(node) => {
        let val = node.borrow().val;
        if val <= target {
          let right = node.borrow().right.clone();
          let res = Self::split_bst(right, target);
          node.borrow_mut().right = res[0].clone();
          vec![Some(node), res[1].clone()]
        } else {
          let left = node.borrow().left.clone();
          let res = Self::split_bst(left, target);
          node.borrow_mut().left = res[1].clone();
          vec![res[0].clone(), Some(node)]
        }
      }
    }
  }
}