Skip to main content
Back to problems
#538
Medium Algorithms

Convert bst to greater tree

Tree Depth-First Search Binary Search Tree Binary Tree
71.4% acceptance
Feb 19, 2026
5404
183
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

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 convert_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
    let mut sum = 0i32;
    fn reverse_inorder(node: &Option<Rc<RefCell<TreeNode>>>, sum: &mut i32) {
      if let Some(n) = node {
        let right = n.borrow().right.clone();
        reverse_inorder(&right, sum);
        *sum += n.borrow().val;
        n.borrow_mut().val = *sum;
        let left = n.borrow().left.clone();
        reverse_inorder(&left, sum);
      }
    }
    reverse_inorder(&root, &mut sum);
    root
  }
}