#1038
Medium Algorithms Binary search tree to greater sum tree
Tree Depth-First Search Binary Search Tree Binary Tree
88.4% acceptance
Feb 27, 2026
4547
169
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)
// 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 bst_to_gst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, acc: &mut i32) {
if let Some(n) = node {
dfs(&n.borrow().right.clone(), acc);
*acc += n.borrow().val;
n.borrow_mut().val = *acc;
dfs(&n.borrow().left.clone(), acc);
}
}
dfs(&root, &mut 0);
root
}
}