Skip to main content
Back to problems
#998
Medium Algorithms

Maximum binary tree ii

Tree Binary Tree
70.3% acceptance
Feb 27, 2026
565
804
A maximum tree is a tree where every node has a value greater than any other value in its subtree. You are given the root of a maximum binary tree and an integer val. Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine: If a is empty, return null. Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i]. The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]). The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]). Return root. Note that we were not given a directly, only a root node root = Construct(a). Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values. Return Construct(b).

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 insert_into_max_tree(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, val: i32) -> Option<std::rc::Rc<std::cell::RefCell<TreeNode>>> {
    if let Some(r) = root {
      if r.borrow().val < val {
        let new_node = std::rc::Rc::new(std::cell::RefCell::new(TreeNode { val, left: Some(r), right: None }));
        return Some(new_node);
      }
      let right = r.borrow().right.clone();
      r.borrow_mut().right = Solution::insert_into_max_tree(right, val);
      Some(r)
    } else {
      Some(std::rc::Rc::new(std::cell::RefCell::new(TreeNode::new(val))))
    }
  }
}